特殊情况下,需要将两个字段不同的实体进行copy(例如:实体A的a,b,c字段需要复制到实体B的1,2,3 字段),且工作量较大时,可使用以下工具类
package com.ibbc.wzbank.service.image.utils;
import java.lang.reflect.Field;
public class EntityCopy {
public static Object copyField(Object source, Object target) {
Field[] a = source.getClass().getDeclaredFields();
Field[] b = target.getClass().getDeclaredFields();
for (int i = 0; i < a.length; i++) {
if (i<= (b.length-1)){
a[i].setAccessible(true);
Object o = null;
try {
o = a[i].get(source);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
b[i].setAccessible(true);
try {
b[i].set(target, o);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
System.out.println(target);
return target;
}
}
测试案例
public static void main(String[] args) {
dog dog = new dog();
dog.setAge(12);
dog.setType("二哈");
dog.setName("哈哈");
cat cat = new cat();
copyField(dog,cat);
System.out.println(cat);
}
public static class dog {
private String name;
private String type;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "dog{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", age=" + age +
'}';
}
}
public static class cat{
private String mingzi;
private String leixing;
private int nianling;
public String getMingzi() {
return mingzi;
}
public void setMingzi(String mingzi) {
this.mingzi = mingzi;
}
public String getLeixing() {
return leixing;
}
public void setLeixing(String leixing) {
this.leixing = leixing;
}
public int getNianling() {
return nianling;
}
public void setNianling(int nianling) {
this.nianling = nianling;
}
@Override
public String toString() {
return "cat{" +
"mingzi='" + mingzi + '\'' +
", leixing='" + leixing + '\'' +
", nianling=" + nianling +
'}';
}
}
测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f8ac26cb0527591693fa46d64797e05a.png#pic_center)