下面是使用的反射的utils 对象的私有属性和公有属性都可以获取到 getDeclaredFields
package com.cn.fs;
import java.lang.reflect.Field;
public class FsUtils {
public static <T> T copyAttr(Object parameter,Object reclazz) {
Field [] fields = parameter.getClass().getDeclaredFields();
if(null!=fields){
for(int i=0;i<fields.length;i++){
Field pojo = fields[i];
String attrName = pojo.getName();
Object attrValue = null;
Field rfield;
try {
pojo.setAccessible(true);
attrValue = pojo.get(parameter);
rfield = reclazz.getClass().getDeclaredField(attrName);
rfield.setAccessible(true);
rfield.set(reclazz, attrValue);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (NoSuchFieldException e) {
continue;
} catch (SecurityException e) {
e.printStackTrace();
} }}
return (T) reclazz;
}}
要进行赋值的PO
package com.cn.fs;
public class Person {
public int age;
public String name;
private int pageSize;
private int pageNum;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}}
传入包含已经有值的
package com.cn.fs;
public class PageAbles {
private int pageSize;
private int pageNum;
private int totalNum;
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getTotalNum() {
return totalNum;
}
public void setTotalNum(int totalNum) {
this.totalNum = totalNum;
}}
测试类
package com.cn.fs;
public class TestFsDemo {
public static void main(String[] args) {
Person pers = new Person();
pers.setAge(20);
pers.setName("zhangsan");
PageAbles pagePo = new PageAbles();
pagePo.setPageNum(5);
pagePo.setPageSize(40);
pagePo.setTotalNum(200);
System.out.println(pers.getName()+".........之前..........."+pers.getPageSize()+"...................."+pers.getPageNum());
pers = FsUtils.copyAttr(pagePo, pers);
System.out.println(pers.getName()+".........之后..........."+pers.getPageSize()+"...................."+pers.getPageNum());
}
}
测试结果如下
zhangsan.........之前...........0....................0
zhangsan.........之后...........40....................5