'Getting All Object attribut names reursively
is there any way to get all attribute names of an object Company
recursively:
ExpectedOutput id, age, address {street, zipCode}, employee {firstName, LastName, profile}, profile {role, experience}.
can we get this output without using SchemaFactoryWrapper
..
class Company{
String id;
int age;
Address address;
List<Employee>
}
class Employee{
String firstName;
String LastName
Profile profile;
}
class Address{
String street;
String zipCode;
}
class Profile{
String role;
int experience
}
Solution 1:[1]
Here is my solution :
private HashSet<String> traverse(Class<?> outputFilter) {
Field[] objectFields = outputFilter.getDeclaredFields();
HashSet<String> fieldNames = new HashSet<>();
for (Field field : objectFields) {
fieldNames.add(field.getName());
if(isValidField(field)){
fieldNames.add("{");
Class<?> clazz = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
fieldNames.addAll(traverse(clazz));
fieldNames.add("}");
}
}
return fieldNames;
}
private boolean isValidField(Field field){
if (field.getType().isAssignableFrom(List.class) |
field.getType().isAssignableFrom(Set.class)){ //TODO Map
Class<?> clazz = ((Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]);
return !clazz.isPrimitive() && !clazz.equals(String.class);
}
else if (field.getType().equals(Object.class) && !field.getType().isPrimitive())
return true;
return false;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |