使用hutool实现entity转map、map转entity,以及entity转entity

时间:2025-02-16 07:04:57
package org.jeecg.common.util.security.entity; import cn.hutool.core.bean.BeanUtil; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.Set; /** * @ClassName: Test * @Author: zengjingchao * @Date: 2023/6/16 15:05 * @Description: **/ public class Test { private String name; private int age; private Date birthday; public Test() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Test test = (Test) o; return age == test.age && Objects.equals(name, test.name) && Objects.equals(birthday, test.birthday); } @Override public int hashCode() { return Objects.hash(name, age, birthday); } @Override public String toString() { return "Test{" + "name='" + name + '\'' + ", age=" + age + ", birthday=" + birthday + '}'; } public static void main(String[] args) { Test test=new Test(); test.setAge(18); test.setBirthday(new Date()); test.setName("张三"); System.out.println(test); System.out.println("-----------"); //bean转map Map<String, Object> objectMap = BeanUtil.beanToMap(test); Set<Map.Entry<String, Object>> entries = objectMap.entrySet(); for (Map.Entry<String,Object> entry:entries){ System.out.println(entry.getKey()+"->"+entry.getValue()); } //map转bean Test test1 = BeanUtil.mapToBean(objectMap, Test.class, true); System.out.println("----------"); System.out.println(test1); System.out.println("------"); Test1 test11=new Test1(); test11.setHigh("180"); test11.setName("李四"); System.out.println(test11); System.out.println("------------"); //字段拷贝,根据字段名进行拷贝,匹配的就拷贝,不匹配的就跳过、 //如果字段名匹配的话就将test的值拷贝到test11,例子里面只有name是两个对象都有的 BeanUtil.copyProperties(test,test11); System.out.println(test11); } }