簡體   English   中英

獲取帶注釋的變量的值

[英]Get the value of the annotated variable

是否有可能獲得帶注釋的變量? 我有一個這樣的變量:

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

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

我想檢索flagElements的值。 可能嗎?

您可以通過這樣對類字段進行反射來實現此@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.
        }
}

但是請確保您的Flag批注具有RetentionPolicy.RUNTIME

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM