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.
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…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With