Annotations on instantiation, such as new @Anno Object() , are not a property of the created object, but only the type (compilation time) of the new expression. At run time, the actual type of the object does not have an annotation, just as it does not have parameters of the Generic type that you could specify when creating the instance.
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, a simple object goes through several changes of the type: 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 two different typed variables, @Anno(1) Object and @Anno(3) Object , at the same time!
You can use audit tools to check if these transitions are legal for any @Anno semantics, but for the Java language itself they have no meaning and will always be accepted. And at run time, the instance type will always be Object not affected by the type annotation.
The Reflection API provides methods for requesting annotated types of declarations of classes and members, which includes types of parameters and return methods, but you cannot request annotations of the type of the expression new , since you cannot find out the method actually contains the expression new , not to mention the types of annotations used to this expression new .
There may be third-party libraries that install bytecode processing libraries that will provide access to these annotations at runtime ...
source share