package com.nuvole.util;
|
|
import org.apache.commons.beanutils.BeanMap;
|
|
import java.beans.BeanInfo;
|
import java.beans.IntrospectionException;
|
import java.beans.Introspector;
|
import java.beans.PropertyDescriptor;
|
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.Method;
|
import java.util.Map;
|
// @formatter:off
|
/**
|
* .-~~~~~~~~~-._ _.-~~~~~~~~~-.
|
* __.' @Author ~. .~ 代码无Bug `.__
|
* .'// liu.q \./ (秘籍) \\`.
|
* .'// [916000612@qq.com] | 欲练神功 引刀自宫 \\`.
|
* .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
|
* .'//.-" 2019-04-07 `-. | .-' 19:44 "-.\\`.
|
* .'//______.============-.. \ | / ..-============.______\\`.
|
*.'______________________________\|/______________________________`.
|
*
|
* @Description : bean map 互相转换工具类
|
*/
|
// @formatter:on
|
public class BeanUtil {
|
|
public static <T> Map<String, Object> bean2Map(T bean, Map<String, Object> mp) {
|
if (bean == null) {
|
return mp;
|
}
|
try {
|
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
|
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
for (PropertyDescriptor property : propertyDescriptors) {
|
String k = property.getName();
|
|
if (!k.equals("class")) {
|
Method getter = property.getReadMethod();// Java中提供了用来访问某个属性的
|
// getter/setter方法
|
Object value;
|
value = getter.invoke(bean);
|
mp.put(k, value);
|
}
|
}
|
} catch (IntrospectionException e) {
|
e.printStackTrace();
|
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
e.printStackTrace();
|
}
|
return mp;
|
|
}
|
|
|
public static <T> T map2Bean(Map<String, Object> mp, Class<T> beanCls) throws IllegalAccessException, InstantiationException, InvocationTargetException, IntrospectionException {
|
T t = null;
|
BeanInfo beanInfo = Introspector.getBeanInfo(beanCls);
|
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
t = beanCls.newInstance();
|
for (PropertyDescriptor property : propertyDescriptors) {
|
String k = property.getName();
|
|
if (mp.containsKey(k)) {
|
Object value = mp.get(k);
|
Method setter = property.getWriteMethod();// Java中提供了用来访问某个属性的
|
// getter/setter方法
|
setter.invoke(t, value);
|
}
|
}
|
return t;
|
}
|
|
public static Map obj2Map(Object obj) {
|
if (obj == null) {
|
return new BeanMap();
|
}
|
return new BeanMap(obj);
|
}
|
}
|