反射是动态统一处理不同Object的方法。不同的方法取出各自的属性名getDeclaredField,或者方法名getDeclaredMethod。若是只有一种Object根本不需要反射来处理,用本Object自己的方法就可以。
- 举例一:传入一个List对象,及该对象的属性名获取该List中所有该属性的值(属性类型为String)
private static List<String> getWybsListValueByName(String fieldName, List list) {
try {
List<String>lists=new ArrayList<>(list.size());
for (Object object:list) {
String firstCode = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstCode + fieldName.substring(1);
Method method = object.getClass().getMethod(getter);
Object value = method.invoke(object);
lists.add(value.toString());
}
return lists;
} catch (Exception e) {
return null;
}
}
- 举例二:获取某个对象全部属性及属性值映射成map
- public static Map getDataList(test test,Object o) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Map<String,Object>map=new HashMap<>();
Field[] declaredFields = o.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
String s = declaredField.toGenericString();
while (s.contains(".")) {
s = s.substring(s.indexOf(".") + 1);
}
String name=s;
//get方法list
s = "get" + s.substring(0, 1).toUpperCase() + s.substring(1);
Object value = o.getClass().getMethod(s).invoke(o);
map.put(name,value);
}
System.out.println("result ======"+map);
return map;
}