简体   繁体   English

获取带注释的变量的值

[英]Get the value of the annotated variable

Is it possible to get the variable which is annotated? 是否有可能获得带注释的变量? I have a variable like this below: 我有一个这样的变量:

  @Flag
  FlagElements flagElements = new FlagElements("key1", "type1", "value1", "desc1");

FlagElements is defined as below: FlagElements定义如下:

public class FlagElements<T>{
  public String key;
  public String type;
  public T value;
  public String description;

  public FlagElements(String key, String type, T value, String description) {
    this.key = key;
    this.type = type;
    this.value = value;
    this.description = description;
  }
}

I want to retrieve the value of flagElements . 我想检索flagElements的值。 Is it possible? 可能吗?

You can achieve this using reflection on your class fields this way you can check if field are annotated with @Flag for instance, bellow a simple example : 您可以通过这样对类字段进行反射来实现此@Flag ,例如,可以检查字段是否用@Flag注释,下面是一个简单的示例:

for(Field field  : TestObject.class.getDeclaredFields())
{
    if (field.isAnnotationPresent(Flag.class))
        {
              Object value = field.get(objectInstance);//objectInstance is an instance of FlagElements, you can instanciate it using the new operator if you know already know the class type or use reflection if you don't know what you'll have as a class.
        }
}

But make sure your Flag annotation has RetentionPolicy.RUNTIME 但是请确保您的Flag批注具有RetentionPolicy.RUNTIME

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

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