代码之家  ›  专栏  ›  技术社区  ›  wittich Manish Shrivastava

通过循环列表从JPA元模型获取SingularAttribute

  •  1
  • wittich Manish Shrivastava  · 技术社区  · 7 年前

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


    使现代化

    我尝试使用java反射,正如 @naXa

    // 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"); 
    }
    

    它不会返回正确的名称或类型(请参阅代码中的输出注释)。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ranjeet    7 年前

    在反射代码中,您直接使用字段,但这不是您要查找的静态SingularAttribute(Test_u.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();
            }
        }
    }