クラスのプロパティ値を反射してコピーする
クラスの属性値を反射コピーする方法:
package com.wansha.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ClassCopy {
public Object copyof(Object object)throws Exception{
Class<?> classType = object.getClass();
Object obj = classType.newInstance();
Field[] fields = classType.getDeclaredFields();
for(Field field : fields){
String fieldName =field.getName().substring(0,1).toUpperCase()+field.getName().substring(1);
Method setmethod = classType.getMethod("set"+fieldName,new Class[]{field.getType()});
Method getmethod = classType.getMethod("get"+fieldName,new Class[]{});
setmethod.invoke(obj,new Object[]{getmethod.invoke(object,new Object[]{})});
System.out.println(setmethod.getName()+"============"+getmethod.getName());
}
return obj;
}
public static void main(String[] args) throws Exception{
ClassCopy copy = new ClassCopy();
Object obj = copy.copyof(new Person2("sharp",30));
System.out.println((Person2)obj);
}
}
class Person2{
private Long id;
private String name;
private int age;
public Person2(String name, int age) {
this.name = name;
this.age = age;
}
public Person2() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "name-->"+name+" age-->"+age;
}
}