mardi 23 janvier 2018

Reflection : Accessing nested bean property using java.beans.Expression

Background : I am using below snipet of code in my java application which can be used to get values of a field/property inside a class.

public static Object getProperty(Object object, String propertyName) {
    Object value;
    Expression expression = new Expression(object, "get" + StringUtils.capitalize(propertyName), new Object[0]);
    try {
        expression.execute();
        value = expression.getValue();
    } catch (Exception e) {
        value = null;
    }
    return value;
}

Now Refer this design

public class EntityA extends ParentEntity{
private String fieldA;
private String fieldB;
//Getters and Setters of above fields
} 

public class ParentEntity {
private String fieldC;
private GrandParentEntity grandParentEntity;

//Getters and Setters of above fields
}

public class GrandParentEntity extends SuperParentEntity{
private String fieldE;
private String fieldF;
//Getters and Setters of above fields
}  

Problem : Using above design scenario, what should I pass in my static method getProperty to access fieldE and fieldF (from GrandParentEntity using EntityA )

Note : I tried to pass

getProperty(new EntityA(),"grandParentEntity.fieldE")

but it gives error : java.lang.NoSuchMethodException: <unbound>=EntityA.getGrandParentEntity.fieldE();





Aucun commentaire:

Enregistrer un commentaire