Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 290
user3475234 Avatar asked Aug 14 '14 19:08

user3475234


1 Answers

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…

like image 78
Holger Avatar answered Nov 01 '22 00:11

Holger