[英]How do I get all fields of embedded classes?
我有一个 Account 类的实例(我们称之为实体):
private String accountType;
private List<String> attributes = new ArrayList<>();
private Date createdDate;
private ContactInfo contactInfo;
private AccountStatus accountStatus;
如您所见,里面有“ContactInfo”和“AccountStatus”类。 如果我拥有实体,如何获取 Account 类中的所有字段及其所有使用的类?
这就是我现在写的,它只返回给定实体中的所有字段。
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;
}
感谢@Andreas new 我已经解决了:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.