主函數:
package gdut.clb.reflect;
public class CopyReflect {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
Student student = new Student() ;
student.setId(new Long(1000)) ;
student.setName("xinzi") ;
student.setAge(22) ;
Student copyStudent = (Student)CopyObject.copy(student) ;
System.out.println("id: "+copyStudent.getId()+" ,name: "+copyStudent.getName()+" age: "+copyStudent.getAge()) ;
}
}
//定義一個Student的類
class Student {
private Long id ;
private String name ;
private int age ;
public Student(){}
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;
}
以下這個類對對象進行復制:
package gdut.clb.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class CopyObject {
public static Object copy(Object object)throws Exception{
Class<?> classType = object.getClass() ;
Object copyObject = classType.getConstructor(new Class[]{}).newInstance(new Object[]{}) ;
Field[] fields = classType.getDeclaredFields() ;
String name = null ;
String setterName = null ;
String getterName = null ;
for(Field field : fields){
name = field.getName() ;
setterName = "set"+name.substring(0,1).toUpperCase()+name.substring(1) ;
getterName = "get"+name.substring(0,1).toUpperCase()+name.substring(1) ;
Method getterMethod = classType.getDeclaredMethod(getterName, new Class[]{}) ;
Method setterMethod = classType.getDeclaredMethod(setterName, field.getType()) ;
setterMethod.invoke(copyObject, new Object[]{getterMethod.invoke(object, new Object[]{})}) ;
}
return copyObject ;
}
}
} 運行結果: