1

I'm having a JPA metamodel where I retrieving attributes from.

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

I can call and use them manually:

Test_.var1
Test_.var2
Test_.var3

But how can I do that by looping through a list:

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)

}

How do I get the attribute from the metamodel using string var.


Update

I tried to use java reflection as suggested by @naXa within the loop but without success:

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

It doesn't return the correct name nor type (see output comments in code).

wittich
  • 2,079
  • 2
  • 27
  • 50

1 Answers1

1

In your Reflection code you are using the field directly but that is not the static SingularAttribute (Test_.var1) value you are looking for. You need to get the actual static value using 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();
        }
    }
}
Ranjeet
  • 859
  • 7
  • 19