1. 直接使用 Springframework 下的工具 BeanUtils 可以进行简单对象的复制拷贝,具体使用方式如下:
类A的信息:
import lombok.Data; import lombok.ToString; @Data public class ClassA { private String name; private String email; private Integer age; }
类B的信息:
import lombok.Data; import lombok.ToString; @Data @ToString public class ClassB { private String name; private String email; }
测试对象拷贝的案例:
import org.springframework.beans.BeanUtils; public class TestAB { public static void main(String[] args) { ClassA classA = new ClassA(); classA.setAge(1); classA.setEmail("test@qq.com"); classA.setName("test A"); ClassB classB = new ClassB(); BeanUtils.copyProperties(classA, classB, ClassB.class); System.out.println(classB); } }
输出结果:
ClassB(name=test A, email=test@qq.com)
2. 如果是对数组进行复制拷贝,则需要写一个 ListBeanUtils 工具类,如下所示:
import java.util.List; import java.util.Objects; public class ListBeanUtils<T> { public void copyList(Object obj, List<T> list2, Class<T> classObj) { if ((!Objects.isNull(obj)) && (!Objects.isNull(list2))) { List list1 = (List) obj; list1.forEach(item -> { try { T data = classObj.newInstance(); BeanUtils.copyProperties(item, data); list2.add(data); } catch (InstantiationException e) { } catch (IllegalAccessException e) { } }); } } }
测试数组拷贝的案例:
import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.List; public class TestAB { public static void main(String[] args) { ClassA classA = new ClassA(); classA.setAge(1); classA.setEmail("test@qq.com"); classA.setName("test A"); ClassA classA1 = new ClassA(); classA1.setAge(12); classA1.setEmail("test2@qq.com"); classA1.setName("test A2"); List<ClassA> aList = new ArrayList<>(); aList.add(classA); aList.add(classA1); List<ClassB> bList = new ArrayList<>(); ListBeanUtils<ClassB> utils = BeanUtils.instantiateClass(ListBeanUtils.class); utils.copyList(aList, bList, ClassB.class); System.out.println(bList); } }
输出结果:
[ClassB(name=test A, email=test@qq.com), ClassB(name=test A2, email=test2@qq.com)]