Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

reflection - Java 8 Annotations on Instance creation

In the Javadocs for Annotations, it states that the following can be written in Java 8:

new @Interned MyObject();

Is there anyway to retrieve the annotation @Interned from an object annotated like this via reflection? I'm familiar with the typical ways of retrieving annotations from methods, fields, classes, etc, but I'd like to know if it's possible to associate a particular instance with an annotation at runtime in Java 8.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An annotation applied to an instance creation like new @Anno Object() is not a property of the created object but only of the (compile-time) type of the new expression. At runtime the actual type of the object does not have the annotation just like it has no Generic type parameters you might have specified at the instance creation.

Just consider the following example:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface Anno { int value(); }

@Anno(1) Object o=new @Anno(2) Object();
@Anno(3) Object p=(@Anno(4) Object)o;

Here, the simple object goes through several type changes, from @Anno(2) Object to @Anno(1) Object to @Anno(4) Object to @Anno(3) Object and at the end of this code the same object is even held by two differently typed variables, @Anno(1) Object and @Anno(3) Object, at the same time!

You may use audit tools to verify whether these type transitions are legal in respect to whatever semantics @Anno implies, but to the Java language itself they have no meaning and will be always accepted. And at runtime, the type of the instance will always be Object not being affected by the type annotation.

The Reflection API provides ways to query the annotated types of declarations of classes and members which includes parameter and return types of methods but you cannot query the type annotations of a new expression as you will not be able to find out whether a method actually contains a new expression, let alone type annotations applied to that new expression.

There might be 3rd party libraries settling on byte code processing libraries which will provide access to these annotations at runtime…


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...