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…
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…