I am trying to get a list of all fields, be it a primitive or not of an object given as an argument to the method getFieldz. I've been trying to figure this out for a while now, the following code is the result. I keep getting stackoverflow error and have no clue why is this happening. Any pointers? Or perhaps I am doing something incorrectly?
Here's the logic: Get all of object's fields, if its a primitive or string add it to the list, otherwise check if the field has any subfields, if not then add it to the list if yes then recursively perform the check for the field.
public List<String> getFieldz(Object object) {
List<String> fieldList = new ArrayList<String>();
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getType().isPrimitive() || fields[i].getType().toString().equals("class java.lang.String")) {
fieldList.add(fields[i].getName());
}
else {
Field[] subFields = fields[i].getClass().getDeclaredFields();
if (subFields.length > 0) {
System.out.println(subFields.length);
getFieldz((Object)fields[i].getClass());
} else {
fieldList.add(fields[i].getName());
}
}
}
return addParrentName(fieldList, object.getClass().getSimpleName());
}
public List<String> addParrentName(List<String> list, String parrentName) {
if (parrentName.equals("Field")) {
return list;
}
List<String> listWithParrentNames = new ArrayList<String>();
for (String name : list) {
listWithParrentNames.add(parrentName + "." + name);
}
return listWithParrentNames;
}
EDIT: It's not that I don't know what stackoverflow error is, I just don't know why am I getting it: which part of the code is causing the infinite loop;
Aucun commentaire:
Enregistrer un commentaire