是否有可能获得带注释的变量?我下面有一个这样的变量:
@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
注释,下面是一个简单的示例:
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