如何获取嵌入式类的所有字段?

时间:2016-07-08 21:03:35

标签: java reflection

我有一个类帐户的实例(让我们称之为实体):

private String accountType;
private List<String> attributes = new ArrayList<>();
private Date createdDate;
private ContactInfo contactInfo;
private AccountStatus accountStatus;

正如您所看到的那样,有一些课程&#34; ContactInfo&#34;和&#34; AccountStatus&#34;内。我怎样才能获得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;
}

1 个答案:

答案 0 :(得分:1)

感谢@Andreas新的我解决了它:

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;
}