内省Introspector实现Bean对象转Map

xiaoxiao2021-02-28  93

直接上代码,把对象放进去就能返回一个Map对象了

private Map<String, Object> objectToMap(Object bindings) throws IntrospectionException, InvocationTargetException, IllegalAccessException { Map<String, Object> data = new HashMap(); //内省 获取对象的信息 BeanInfo beanInfo = Introspector.getBeanInfo(bindings.getClass()); //获取特性 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); //遍历特性 for (PropertyDescriptor propertyDescriptor : propertyDescriptors){ //获取属性名 String key = propertyDescriptor.getName(); if (key.equals("class")){ continue; } //获取对应属性的get方法 Method getter = propertyDescriptor.getReadMethod(); //执行方法 Object value = getter!=null ? getter.invoke(bindings) : null; data.put(key,value); } return data; }当然还有一种情况是如果遇到类对象里面还有类对象怎么办?只需要在上面的方法中修改一下,添加一个递归

private Map<String, Object> objectToMap(Object bindings) throws IntrospectionException, InvocationTargetException, IllegalAccessException { Map<String, Object> data = new HashMap(); //内省 获取对象的信息 BeanInfo beanInfo = Introspector.getBeanInfo(bindings.getClass()); //获取特性 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); //遍历特性 for (PropertyDescriptor propertyDescriptor : propertyDescriptors){ //获取属性名 String key = propertyDescriptor.getName(); if (key.equals("class")){ continue; } //获取对应属性的get方法 Method getter = propertyDescriptor.getReadMethod(); //执行方法 Object value = getter!=null ? getter.invoke(bindings) : null; //判断是否是对象中的对象 if (judgeIsObjectInObject(value)){ //如果是,则递归,返回Map value = objectToMap(value); } data.put(key,value); } return data; }还有一个判断的方法要用到

private boolean judgeIsObjectInObject(Object object) { boolean IsObjectInObject = false; //排除基本类型 if (object instanceof Integer){ return IsObjectInObject; } else if (object instanceof String){ return IsObjectInObject; } else if (object instanceof Float){ return IsObjectInObject; } else if (object instanceof Double){ return IsObjectInObject; }else { IsObjectInObject = true; } return IsObjectInObject; } 另外如果要在android中使用,则需要导入openBean包,因为android阉割掉了Javabean的很多类

转载请注明原文地址: https://www.6miu.com/read-64204.html

最新回复(0)