public static void main(String[] args) {
// TODO Auto-generated method stub
Result result = new Result<>();
//实现将Javabean的属性值循环存入map中
Map<String, Object> map = new LinkedHashMap<>();
try {
PropertyDescriptor[] properties = Introspector.getBeanInfo(Result.class).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : properties) {
String propertyName= propertyDescriptor.getName();
if (!propertyName.equals("class")) {
Method method = propertyDescriptor.getReadMethod(); //只是获取到getter方法 并不能知道是谁的
Object value = method.invoke(result); // 告诉电脑这个方法是哪个类的,然后获取值
map.put(propertyName, value);
System.out.println(map);
}
}
// 对象即使是拥有相同键的map对象也不能复制属性给Map对象
Map map3 = new LinkedHashMap<>();
map3.put("code",0);
map3.put("data", null);
map3.put("msg", "");
BeanUtils.copyProperties(map3, map);
System.out.println("**********"+map3);
BeanUtils.copyProperties(map3, result);
System.out.println("************"+map3);
//将map的值依次赋给相应的属性
map.put("code", 3);
map.put("data", "test");
map.put("msg", "lala");
for (PropertyDescriptor propertyDescriptor : properties) {
String propertyName = propertyDescriptor.getName();
if (propertyName.equals("class")) {
continue;
}
Object value = map.get(propertyName);
BeanUtils utils = new BeanUtils();
BeanUtils.copyProperty(result, propertyName, value);
}
System.out.println("***********************************");
System.out.println(result);
System.out.println("***********************************");
// 拥有相同键的Map对象可以直接赋值给对象的相应属性
Map map2 = new LinkedHashMap<>();
map2.put("code", 4);
map2.put("data", "tttttt");
map2.put("msg", "hahhahaahah");
map2.put("nae", "jdflkdj");
BeanUtils.copyProperties(result, map2);
System.out.println(result.toString());
} catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}