cn.sylinx.hbatis.kit.BeanUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hbatis-core Show documentation
Show all versions of hbatis-core Show documentation
hbatis is a simple orm framework
The newest version!
package cn.sylinx.hbatis.kit;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class BeanUtil {
// 把JavaBean转化为map
public static Map bean2map(Object bean) {
try {
return bean2mapInner(bean);
} catch (Exception e) {
return new HashMap();
}
}
// 把JavaBean转化为map
private static Map bean2mapInner(Object bean) throws Exception {
Map map = new HashMap<>();
// 获取JavaBean的描述器
BeanInfo b = Introspector.getBeanInfo(bean.getClass(), Object.class);
// 获取属性描述器
PropertyDescriptor[] pds = b.getPropertyDescriptors();
// 对属性迭代
for (PropertyDescriptor pd : pds) {
// 属性名称
String propertyName = pd.getName();
// 属性值,用getter方法获取
Method m = pd.getReadMethod();
Object properValue = m.invoke(bean);// 用对象执行getter方法获得属性值
// 把属性名-属性值 存到Map中
map.put(propertyName, properValue);
}
return map;
}
}