访问带注释的字段 [英] Access annotated fields

查看:135
本文介绍了访问带注释的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



@MyAnnotation int myVariable



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



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



关于如何做的任何建议?



提前致谢!! :)


解决方案

  INT getMyVariable(美孚富)抛出:IllegalArgumentException  - ,IllegalAccessException {
for(Field f:foo.getClass()。getDeclaredFields()){
/ **
*确保'MyAnnotation'的RetentionPolicy为RUNTIME。
* /
if(f.isAnnotationPresent(MyAnnotation.class)){
return f.getInt(foo);
}
}
返回-1;
}


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

解决方案

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

这篇关于访问带注释的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆