How can I read read the value of a Java method annotation at runtime with ASM ?
The Annotation has only a CLASS
RetentionPolicy
, so it's not possible to do that with Reflections.
| Policy CLASS
: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time
Example:
I want to extract the value Carly Rae Jepsen
out of the artist
field at runtime:
public class SampleClass {
@MyAnnotation(artist = "Carly Rae Jepsen")
public void callMeMaybe(){}
}
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String artist() default "";
}
But why?
Can't you just change the RetentionPolicy
to RUNTIME
and do it with reflections?
In short: No. I use the modelmapper framework (Simple, Intelligent, Object Mapping). There I specify bidirectional mappings between Java classes by annotated methods. I wan't to reuse this information of hierarchical mappings, for change event propagation. But the provided mapstruct org.mapstruct.Mapping
Annotation has CLASS RetentionPolicy
. This is why I need to read that information out of the class files - and need ASM.