So my problem is that im currently trying to use java's reflection to traverse a tree like structure. The problem is the only thing i know about each structure is that it can contain one of three things. Strings (the leaf's) Other Objects, Or Lists of other objects. Using reflection i want to do a DFS of the tree until i find a node that im looking for. My problem seems to be that when i use reflection to get a field that happens to be of type List i get back List and i am unable to down cast the the correct type. here are some samples i have tried.
Using Fields
Object returnObj = new Object();
Field field = object.getClass().getDeclaredField(fieldClassName);
field.setAccessible(true);
List<DistributionPartnerRoleType> test = (List<DistributionPartnerRoleType>) field.get(object);
And using Methods
String methodName = "get" + Character.toUpperCase(fieldClassName.charAt(0)) + fieldClassName.substring(1);
Method[] getters = object.getClass().getMethods();
Method getter = getMethod(getters, methodName);
Type returnType = getter.getGenericReturnType();
if(returnType instanceof ParameterizedType){
Type actualType = ((ParameterizedType) returnType).getActualTypeArguments()[0];
Class actualClass = (Class) actualType;
returnObj = getter.invoke(object, null);
List<Object> newList = new ArrayList<Object>();
for(Object obj : (List<Object>)returnObj){
newList.add(actualClass.cast(obj));
}
returnObj = newList;
}
Im aware that the problem is that the objects are truly of type Object but the function and fields are explicitly of type List as declared in the code
protected List<DistributionPartnerRoleType> distributionPartnerRole;
public List<DistributionPartnerRoleType> getDistributionPartnerRole() {
if (distributionPartnerRole == null) {
distributionPartnerRole = new ArrayList<DistributionPartnerRoleType>();
}
return this.distributionPartnerRole;
}
If anyone knows of a solution for this problem that would be great, Or if i need to go about a different method other then reflection.
edit - code block
Aucun commentaire:
Enregistrer un commentaire