1,自己实现;

/**
* @author xx
* @since 2020/7/8
*/
@Slf4j
public class JavaBeanUtils { /**
* 实体类转map
* 效率较低
*
* @param obj
* @return
*/
public static Map<String, Object> convertBeanToMap(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>(16);
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
if (null == value) {
map.put(key, "");
} else {
map.put(key, value);
}
}
}
} catch (Exception e) {
log.error("convertBean2Map Error:", e);
}
return map;
} /**
* map 转实体类
*
* @param clazz
* @param map
* @param <T>
* @return
*/
public static <T> T convertMapToBean(Class<T> clazz, Map<String, Object> map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
// 创建 JavaBean 对象
obj = clazz.newInstance();
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : propertyDescriptors) {
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
if ("".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
}
}
} catch (IllegalAccessException e) {
log.error("convertMapToBean 实例化JavaBean失败 Error:", e);
} catch (IntrospectionException e) {
log.error("convertMapToBean 分析类属性失败 Error:", e);
} catch (IllegalArgumentException e) {
log.error("convertMapToBean 映射错误 Error:", e);
} catch (InstantiationException e) {
log.error("convertMapToBean 实例化 JavaBean 失败 Error:", e);
} catch (InvocationTargetException e) {
log.error("convertMapToBean字段映射失败 Error:", e);
} catch (Exception e) {
log.error("convertMapToBean Error:", e);
}
return (T) obj;
} /**
* 将map通过反射转化为实体
*
* @param map
* @param obj
* @return
* @throws Exception
*/
public static Object mapToModel(Map<String, Object> map, Object obj) throws Exception {
if (!map.isEmpty()) {
for (String key : map.keySet()) {
Object value = null;
if (!key.isEmpty()) {
value = map.get(key);
}
Field[] fields = null;
fields = obj.getClass().getDeclaredFields();
String clzName = obj.getClass().getSimpleName();
for (Field field : fields) {
int mod = field.getModifiers();
if (field.getName().toUpperCase().equals(key.toUpperCase())) {
field.setAccessible(true);
//进行类型判断
String type = field.getType().toString();
if (Objects.isNull(value)) {
continue;
}
if (type.endsWith("String")) {
value = value.toString();
}
if (type.endsWith("Date")) {
value = new Date(value.toString());
}
if (type.endsWith("Boolean")) {
value = Boolean.getBoolean(value.toString());
}
if (type.endsWith("int")) {
value = new Integer(value.toString());
}
if (type.endsWith("Long")) {
value = new Long(value.toString());
}
field.set(obj, value);
}
}
}
}
return obj;
} /**
* 实体对象转成Map
*
* @param obj 实体对象
* @return
*/
public static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap<>(16);
if (obj == null) {
return map;
}
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
log.error("object2Map Error:", e);
}
return map;
} /**
* Map转成实体对象
*
* @param map map实体对象包含属性
* @param clazz 实体对象类型
* @return
*/
public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
} catch (Exception e) {
log.error("map2Object Error:", e);
}
return obj;
} public static void main(String[] args) { Student s = new Student();
s.setUserName("ZHH");
s.setUserName2("ZHH");
s.setUserName3("ZHH");
s.setUserName4("ZHH");
s.setUserName5("ZHH");
s.setDate(new Date());
s.setAge(24);
long sss = System.currentTimeMillis();
System.out.println("==" + object2Map(s));
long ddd = System.currentTimeMillis();
//0ms
System.out.println(ddd - sss); Map<String, Object> map = new HashMap<>(4);
map.put("userName", "zhh");
map.put("userName2", "zhh");
map.put("userName3", "zhh");
map.put("userName4", "zhh");
map.put("userName5", "zhh");
map.put("age", 24);
map.put("date", new Date()); long aaa = System.currentTimeMillis();
System.out.println("++" + map2Object(map, Student.class));
long www = System.currentTimeMillis();
//0ms
System.out.println(www - aaa); long q = System.currentTimeMillis();
System.out.println("==22++" + convertBeanToMap(s));
long f = System.currentTimeMillis();
//16ms
System.out.println(f - q); try {
// DateTime parse = DateUtil.parse(new Date().toString());
//
// System.out.println("date:" + parse);
} catch (Exception e) {
e.printStackTrace();
} long c = System.currentTimeMillis();
System.out.println("==22++" + convertBeanToMap(s));
long d = System.currentTimeMillis();
//0ms
System.out.println(d - c); long a = System.currentTimeMillis();
System.out.println("++22==" + convertMapToBean(Student.class, map));
long b = System.currentTimeMillis();
//0ms
System.out.println(b - a); try {
long start = System.currentTimeMillis();
System.out.println("++3333333==" + mapToModel(map, new Student()).toString());
long end = System.currentTimeMillis();
//0ms
System.out.println(end - start);
} catch (Exception e) {
e.printStackTrace();
}
} } 2,也可以直接使用Hutool提供的MapUtil实现

  

最新文章

  1. springmvc 用注解方式添加事务不生效解决方法
  2. mysql 行转列 和 列转行
  3. 基于uploadify.js实现多文件上传和上传进度条的显示
  4. JSONP理解和使用
  5. JDK中的URLConnection参数详解
  6. [redis] Redis 配置文件置参数详解
  7. iOS开发之多媒体API(1)
  8. 关于RtlInitUnicodeString感想
  9. 列举一些常见的Python HTTP服务器
  10. Erlang使用ProtoBuffer
  11. Struts2 之值栈
  12. vs文件上传失败--超过最大字符限制
  13. 判断字符串是否为正整数 &amp; 浮点小数
  14. macOS下通过docker在局域网成功访问mysql5.6数据库
  15. java Serializable和Externalizable序列化反序列化详解(转载)
  16. leetcode 184 部门工资最高的员工
  17. P2042 [NOI2005]维护数列 &amp;&amp; Splay区间操作(四)
  18. ASP.NET MVC4+EasyUI+EntityFrameWork5权限管理系统——数据库的设计(一)
  19. C++ Class与Struct的区别
  20. odex反编译dex异常 Cannot locate boot class path file /system/framework/core.odex

热门文章

  1. vm中安装win2012并安装hyper-V不支持嵌套
  2. vm 将宿主机文件夹 映射至 虚拟机
  3. Hive语法及其进阶(一)
  4. 生动直观的Gif图告诉你如何安装Python安装第3方库,在线安装离线安装全都搞定
  5. ASP.NET Core 5.0 中读取Request中Body信息
  6. AOJ/树与二叉搜索树习题集
  7. CSS3思维导图
  8. SpringBoot入门03-转发到Thymeleaf
  9. pycharm中设置自己的文件模板
  10. perl Encode模块的使用