访问带注释的字段

biq*_*llo 16 java reflection annotations

我为我的项目制作了一个自定义注释,它只用于字段,即

@MyAnnotation int myVariable

我有另一个类,它将负责根据变量值执行一些操作.项目具有未确定数量的类,其中包含注释.如何使用我的注释处理器访问它们以访问值?

我可以检查每个类的注释变量,但不修改值,因为它不是一个对象.

关于如何做的任何建议?

提前致谢!!:)

卢声远*_* Lu 20

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;
}
Run Code Online (Sandbox Code Playgroud)