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;
}
}