java 访问带注释的字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3796691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:25:07  来源:igfitidea点击:

Access annotated fields

javareflectionannotations

提问by biquillo

I made a custom Annotation for my project which will be used only with fields, that is

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

@MyAnnotation int myVariable

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

提前致谢!!:)

回答by u290629

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;
}