是否可以获取带注释的变量?我的变量如下:
@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
的值。有可能吗?
答案 0 :(得分:1)
您可以通过对类字段进行反射来实现此目的,例如,可以检查字段是否用@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