通过反射克隆对象

package Reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class Test {
   public Object copyObj(Person person)throws Exception{
    Object obj = null;//克隆对象
    //获取源对象的Class
    Class c = person.getClass();
    //调用构造方法,创建对象
    obj = c.getConstructor(new Class[] {}).newInstance(new Object[] {});
    //获得对象中的所有属性
    Field[] fs = c.getDeclaredFields();//age  name
    for(int i=0;i<fs.length;i++){
     //组装get方法:1.get、2.属性中第一个字母大写、3.除第一个字母外其余字母相同
    
     Field f = fs[i];
     String fieldName=f.getName();
     //获取属性中第一个字母大写:age Age
     String firstLetter = fieldName.substring(0,1).toUpperCase();
     String getMethodName = "get"+firstLetter+fieldName.substring(1);
     //组装set方法:1.set、2.属性中第一个字母大写  3.除第一个字母外其余相同setAge
     String setMethodName = "set"+firstLetter+fieldName.substring(1);
    
     //获取指定的方法
     //get
     Method getMethod = c.getDeclaredMethod(getMethodName, new Class[] {});
     //set
     Method setMethod = c.getDeclaredMethod(setMethodName, new Class[] {f.getType()});
    
     //执行方法
     //get(源对象的get)
     Object value = getMethod.invoke(person,new Object[] {});
     //set
     setMethod.invoke(obj, value);
    
    
    
    }
    return obj;
   }
 
 public static void main(String[] args) throws Exception {
 //构建源对象
 Person c = new Person("jojgoigj","24");
 
 
 System.out.println("+++++++++源对象++++++++++");
    System.out.println(c.getAge()+"\t"+c.getName());
   
    Test t = new Test();
    Person per=(Person)t.copyObj(c);//克隆对象
    System.out.println("===========21=====");
    System.out.println(per.getAge()+"\t"+per.getName());
 }

}

package Reflection;

public class Person {
 String name;
 String age;
public Person() {
 super();
 // TODO Auto-generated constructor stub
}
public Person(String name, String age) {
 super();
 this.name = name;
 this.age = age;
}
public String getName() {
 return name;
}
public void setName(String name) {
 this.name = name;
}
public String getAge() {
 return age;
}
public void setAge(String age) {
 this.age = age;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42044486/article/details/80215330
今日推荐