?
一、获取属性或值并赋值(两种方式)
1、方式一
try {
Class clazz = object.getClass();
Object state = new PropertyDescriptor("name", clazz).getReadMethod().invoke(object);
Method method = clazz.getSuperclass().getMethod("setName", String.class);
method.invoke(object, "倔强男孩儿");
} catch (IntrospectionException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
2、方式二
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
System.out.println("属性:" + field.getName() + " -> 值:" + field.get(object));
String methodName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
Method method = object.getClass().getMethod(methodName, String.class);
method.invoke(object, "倔强男孩儿");
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
二、List转换Map
List<Object> list = new ArrayList<>();
for (Object obj : list) {
Map<String, Object> map = new HashMap<>();
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
if (method.getName().startsWith("get")) {
String name = method.getName().substring(3);
name = name.substring(0, 1).toLowerCase() + name.substring(1);
String type = method.getReturnType().getName();
Object value = null;
try {
if (method.invoke(obj) != null && type.equals("java.util.Date")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(method.invoke(obj).toString());
value = format.format(date);
} else {
value = method.invoke(obj);
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
map.put(name, value);
}
}
}
```
|