可以在运行时在java中使用注释读取字段值吗?

时间:2015-10-01 21:13:24

标签: java reflection annotations

我有一个类跟随,有MyAnnotation:

public class MyClass {

    @MyAnnotation
    public boolean bool;

    public boolean getBool(){
        return bool;
    }

    public voud setBool(boolean b){
        bool = b;
    }
}

可以通过注释在运行时获取bool的值吗?

编辑: 这就是我在寻找:

     public void validate(Object o) throws OperationNotSupportedException {

          Field[] flds = o.getClass().getDeclaredFields();
          for (Field field : flds) {
             if (field.isAnnotationPresent(NotNull.class)) {
                String fieldName = field.getName();
                Method m;
                Object value;

                try {
                   m = o.getClass().getMethod("get" + capitalize(fieldName), null);
                   value = m.invoke(o, null);
                   if (value == null) {
                      throw new OperationNotSupportedException("Field '" + fieldName + "' must be initialized.");
                   }
                } catch (Exception e) {
                   e.printStackTrace();
                }
             }
          }
       }
   private String capitalize(final String line) {
      return Character.toUpperCase(line.charAt(0)) + line.substring(1);
   }

1 个答案:

答案 0 :(得分:1)

不确定这是否是您正在寻找的,但您可以这样做:

Object getValueForMyAnnotaion(MyClass obj) {
   Field[] fieldList = obj.getClass().getDeclaredFields();

   for (Field field : fieldList) {
       if (field.isAnnotationPresent(MyAnnotation.class)) {
          return field.get(obj);
       }
   }
}

请注意,它将返回Object,仅适用于具有注释的第一个成员,但可以轻松更改为您需要的内容。

相关问题