在java中可以在运行时读取带有注释的字段值吗?

It is possible to read the field value with annotations at runtime in java?

我有一个 class 喜欢关注,带有 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);
   }

不确定这是否是您要查找的内容,但您可以这样做:

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

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

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