1.泛型对象,非私有属性,有ReadMethod
实现思路反射,获取Object实际class与bean属性,调用readMethod读取属性
public Map<String, Object> transBean2Map(Object obj) {
if (obj == null) {
return Collections.emptyMap();
}
Map<String, Object> map = new HashMap<>(10);
try {
java.beans.BeanInfo beanInfo = java.beans.Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (java.beans.PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if ("allFields".equals(key)) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
LOG.debug("getter {}", getter);
Object value = getter.invoke(obj);
LOG.debug("key: {},value: {}", key, value);
map.put(key, value);
Map<Object, Object> allValues = (Map<Object, Object>) value;
allValues.forEach((key1, value1) -> {
String fieldKey = ((com.google.protobuf.Descriptors.FieldDescriptor) key1).getName();
map.put(fieldKey, value1);
});
}
}
} catch (Exception e) {
LOG.error("transBean2Map Error ", e);
}
return map;
}
2. 私有属性
Class<?> clusterType = clusterDescriptor.getClass();
Field clusterField = clusterType.getDeclaredField("yarnPb");
clusterField.setAccessible(true);
ApplicationReportPBImpl yarnPb = (ApplicationReportPBImpl) clusterField.get(clusterDescriptor);