Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access annotated fields

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!! :)

like image 844
biquillo Avatar asked Sep 26 '10 05:09

biquillo


People also ask

What are field annotations?

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.

How do you find a class annotation?

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.

How do you inherit annotations?

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.


1 Answers

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;
}
like image 104
卢声远 Shengyuan Lu Avatar answered Oct 04 '22 17:10

卢声远 Shengyuan Lu