If I have a parametrized annotation which is used on a field, can the object referenced by the field access the annotation parameter?
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Classy {
Class<?> klazz();
}
usage:
class Bar{
@Classy(klazz=Integer.class)
Foo foo;
...
}
hypothetical access:
class Foo{
private Class<?> klazz = String.class;
private void useAnnotationParameterIfAvailable(){
klazz = what goes here?
}
}
Thank you
No – annotations are an attribute of the field, and the object can not iterate the fields currently referencing it (To efficiently find the fields, the JVM would have to maintain a dedicated lookup data structure, and update that upon every field assignment. This would be very expensive …)
Of course, if the type of the object uniquely identifies the field, you could employ class path scanning to find all annotated fields of that type – but if the type identifies the class to use, putting the annotation on the type would be far easier 🙂