简体   繁体   English

是否可以在运行时在Java中读取带注释的字段值?

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

I have a class like follow, with MyAnnotation: 我有一个类似以下的类,带有MyAnnotation:

public class MyClass {

    @MyAnnotation
    public boolean bool;

    public boolean getBool(){
        return bool;
    }

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

It is possible to get the value of bool at runtime through the annotation? 是否可以通过注释在运行时获取bool的值?

EDIT: this is that I was looking for: 编辑:这是我在寻找:

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

Not sure if this is what you're looking for but you can do something like this: 不知道这是您要找的东西,但是您可以执行以下操作:

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

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

Note that it will return Object and only for the first member that has the annotation but it can be easily changed to what you need. 请注意,它将仅返回具有注释的第一个成员的Object ,但可以轻松将其更改为所需的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM