package com.fu.demo;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectDemo {
public static void main(String[] args) throws Exception {
ReflectDemo re=new ReflectDemo();
StudentTest stu= (StudentTest)re.copy(new StudentTest(1,"dawson",29));
System.out.println(stu.getId()+"--"+stu.getAge()+"--"+stu.getName());
}
public Object copy(Object obj) throws Exception{
Class<?> classType=obj.getClass();//擷取類的class對象 其他兩種方式:1、類名.class 2、Class.forName(className)
//Method m=classType.getMethod("StudentTest", new Class[]{int.class,String.class,int.class});//使用class對象擷取該類指定的方法
Constructor constructor= classType.getConstructor(new Class[]{}); //classType.getConstructor(new Class[]{int.class,String.class,int.class});//通過class對象擷取構造函數
//Object result=constructor.newInstance(new Object[]{1,"dawson",29});//建立對象 也可以通過classType.newInstance()建立對象 ,不過該方法調用的是無參數的構造函數
Object result=constructor.newInstance(new Object[]{});//通過無參構造函數建立對象
Field[] fileds=classType.getDeclaredFields();//通過class對象擷取該類得所有屬性
for(Field field : fileds){
String MethodName=field.getName().substring(0,1).toUpperCase()+field.getName().substring(1);//擷取屬性名稱 并且把該屬性得首字母轉換成大寫
Method getM=classType.getMethod("get"+MethodName, new Class[]{});//得到該屬性得get方法
Method setM=classType.getMethod("set"+MethodName, new Class[]{field.getType()});//得到該屬性得Set方法
Object fieldResult= getM.invoke(obj, new Object[]{});//擷取該屬性的get值
setM.invoke(result, new Object[]{fieldResult});//将該屬性的get放入copy對象中
}
return result;
}
}
class StudentTest{
public StudentTest(){
}
public StudentTest(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
}
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int 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;
}
}