简体   繁体   中英

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:

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 . 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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