I made a custom Annotation for my project which will be used only with fields, that is
@MyAnnotation int myVariable
I have another class which will be in charge of performing some actions according to the variables values.The project has an undetermined number of classes with annotations included. How can I access them using my annotations processor in order to access the values?
I can check the annotated variables going though each class, but not modifying the value since is not an object.
any suggestion on how to do it?
Thanks in advance!! :)
The getAnnotation() method of java. lang. reflect. Field is used to return returns Field objects's for the specified type if such an annotation is present, else null.
The getAnnotation() method of java. lang. Class class is used to get the annotation of the specified annotation type, if such an annotation is present in this class. The method returns that class in the form of an object.
Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it. The annotation can be overridden in case the child class has the annotation.
int getMyVariable(Foo foo) throws IllegalArgumentException, IllegalAccessException{
for(Field f:foo.getClass().getDeclaredFields()){
/**
* Ensure the RetentionPolicy of 'MyAnnotation' is RUNTIME.
*/
if(f.isAnnotationPresent(MyAnnotation.class)){
return f.getInt(foo);
}
}
return -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With