I have an instance of class Account (let's call it entity):
private String accountType;
private List<String> attributes = new ArrayList<>();
private Date createdDate;
private ContactInfo contactInfo;
private AccountStatus accountStatus;
As you can see there are classes "ContactInfo" and "AccountStatus" inside. How can I get all fields in Account class and all it's used classes providing that I have the entity?
This is what I write now, which only return all the fields in given entity.
private static <T> List<Field> getFields(T entity) {
List<Field> fields = new ArrayList<>();
Class clazz = entity.getClass();
PropertyDescriptor[] propertyDescriptors;
try {
propertyDescriptors = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
} catch (IntrospectionException e) {
// do something
}
for (PropertyDescriptor pd : propertyDescriptors) {
Field field = null;
Class klass = clazz;
while (klass != null && field == null) {
try {
field = klass.getDeclaredField(pd.getName());
} catch (NoSuchFieldException e) {
klass = klass.getSuperclass();
}
}
fields.add(field);
}
return fields;
}
Thanks to @Andreas new I have it solved:
private static <T extends BaseEntity> List<Field> getFields(T entity) {
List<Field> fields = new ArrayList<>();
Class clazz = entity.getClass();
PropertyDescriptor[] propertyDescriptors;
try {
propertyDescriptors = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
} catch (IntrospectionException e) {
return fields;
}
for (PropertyDescriptor pd : propertyDescriptors) {
List<Field> subFields = getSettableFields(pd.getPropertyType());
if (subFields.isEmpty()) {
try {
fields.add(clazz.getDeclaredField(pd.getName()));
} catch (NoSuchFieldException e) {
return fields;
}
} else {
fields.addAll(subFields);
}
}
return fields;
}
private static List<Field> getFields(Class<?> clazz) {
List<Field> fields = new ArrayList<>();
PropertyDescriptor[] propertyDescriptors;
try {
propertyDescriptors = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
} catch (IntrospectionException e) {
return fields;
}
for (PropertyDescriptor pd : propertyDescriptors) {
try {
fields.add(clazz.getDeclaredField(pd.getName()));
} catch (NoSuchFieldException e) {
return fields;
}
}
return fields;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.