我有一个JPA元模型,我从中检索属性。
@StaticMetamodel(Test.class)
public class Test_{
public static volatile SingularAttribute<Test, Boolean> var1;
public static volatile SingularAttribute<Test, Boolean> var2;
public static volatile SingularAttribute<Test, Boolean> var3;
}
我可以手动调用和使用它们:
Test_.var1
Test_.var2
Test_.var3
但是我怎么能通过循环列表来做到这一点:
List<String> vars = new ArrayList<String>();
vars.add("var1");
vars.add("var2");
vars.add("var3");
for (int i=0; i < vars.size(); i++) {
String var = vars.get(i).toString();
System.out.println(var); // prints: var1, var2, var3
// How? (s. update below)
}
如何使用字符串var
从元模型中获取属性。
我试图在循环中使用@naXa建议的java反射,但没有成功:
// suppose to be
System.out.println(Test_.var1); // com.example.entities.Test.var1
System.out.println(Test_.var1.getType()); // boolean
// looping through list
Class object = Test_.class;
try {
Field field = object.getDeclaredField(var);
field.setAccessible(true); // public static volatile javax.persistence.metamodel.SingularAttribute com.example.entities.Test.var1
System.out.println(field); // com.example.entities.Test.var1
System.out.println(field.getType()); // interface javax.persistence.metamodel.SingularAttribute
// but <field> is still no Expression <Boolean>
} catch(NoSuchFieldException e) {
System.out.println("Error");
}
它不会返回正确的名称或类型(请参阅代码中的输出注释)。
答案 0 :(得分:1)
在您的反射代码中,您直接使用该字段,但这不是您要查找的静态SingularAttribute(Test_.var1)值。您需要使用field.get(null)
Field[] fields = Test_.class.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isPublic(field.getModifiers())) {
// For Each Public Field
try {
Object obj = field.get(null); // Equivalent to Test_.var1 but you need to cast it
if (obj instanceof SingularAttribute) {
System.out.println(obj); // Equivalent to Test_.var1
System.out.println(SingularAttribute.class.cast(obj).getType()); // Equivalent to Test_.var1.getType()
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}