簡體   English   中英

如何獲取嵌入式類的所有字段?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM