How to get all child class object from parent class object and put in map java spring
如何从父类对象获取所有子类对象并放入映射java spring
public static Map<String, Object> ConvertObjectToMap(Object obj, Integer number) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> pomclass = obj.getClass();
pomclass = obj.getClass();
Method[] methods = obj.getClass().getMethods();
Map<String, Object> map = new HashMap<String, Object>();
for (Method m : methods) {
if (m.getName().startsWith("get") && !m.getName().startsWith("getClass")) {
Object value = null;
value = (Object) m.invoke(obj);
if (number <= 1) {
if (value.getClass().isAnnotation()) {
map.putAll(ConvertObjectToMap(value, number++));
} else {
map.put(m.getName().substring(3), (Object) value);
}
}
}
}
return map;
}
is this correct ?
它是否正确 ?
1 个解决方案
#1
0
So you want a map of property-name to its value if I understand you correctly.
所以如果我理解正确的话,你想要一个property-name的地图。
How about using commons-beanutils instead of writing this yourself? Something along the lines of
如何使用commons-beanutils而不是自己编写?有点像
import org.apache.commons.beanutils.PropertyUtils;
public static Map<String, Object> ConvertObjectToMap(Object obj, Integer number) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return PropertyUtils.describe(obj);
}
Above code will call all getters, so that'll be the same as yours. If you want to filter the "class" property you can just call .remove("class") on the map returned by describe.
上面的代码会调用所有的getter,这样就和你的一样。如果要过滤“class”属性,可以在describe返回的地图上调用.remove(“class”)。
More info: commons-beanutils homepage
更多信息:commons-beanutils主页
#1
0
So you want a map of property-name to its value if I understand you correctly.
所以如果我理解正确的话,你想要一个property-name的地图。
How about using commons-beanutils instead of writing this yourself? Something along the lines of
如何使用commons-beanutils而不是自己编写?有点像
import org.apache.commons.beanutils.PropertyUtils;
public static Map<String, Object> ConvertObjectToMap(Object obj, Integer number) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return PropertyUtils.describe(obj);
}
Above code will call all getters, so that'll be the same as yours. If you want to filter the "class" property you can just call .remove("class") on the map returned by describe.
上面的代码会调用所有的getter,这样就和你的一样。如果要过滤“class”属性,可以在describe返回的地图上调用.remove(“class”)。
More info: commons-beanutils homepage
更多信息:commons-beanutils主页