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

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

问题描述

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

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?

提前致谢!!:)

推荐答案

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天全站免登陆