通过反射方式复制对象:
1 package cn.tx.reflect; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.Field; 5 import java.lang.reflect.Method; 6 7 /** 8 * 反射复制对象 9 * @author Administrator 10 * 11 */ 12 public class ReflectLearn5 { 13 14 public static void main(String[] args) throws Exception { 15 Person p = new Person(3,"jack","america"); 16 Object obj = copyOjbect(p); 17 System.out.println(obj); 18 } 19 20 public static Object copyOjbect(Object obj) throws Exception{ 21 //获得传递过来的对象的属性和构造器 22 Class<? extends Object> class1 = obj.getClass(); 23 Field[] fields = class1.getDeclaredFields(); 24 Constructor constructor = class1.getConstructor(); 25 Object instance = constructor.newInstance(null); 26 for (Field f : fields) { 27 //获得属性名字 28 String name = f.getName(); 29 //获得属性类型 30 Class<?> type = f.getType(); 31 //获得属性对应的set方法 32 String setMethodName = "set"+ name.substring(0,1).toUpperCase()+name.substring(1); 33 String getMethodName = "get"+ name.substring(0,1).toUpperCase()+name.substring(1); 34 //获得get方法 35 Method gmethod = class1.getDeclaredMethod(getMethodName, null); 36 //调用get方法获得被复制对象的一个属性值 37 Object gresult = gmethod.invoke(obj, null); 38 //get方法的参数类型是string,返回值类型也是 39 Method smethod = class1.getDeclaredMethod(setMethodName,type); 40 // Method smethod = class1.getDeclaredMethod(setMethodName,gmethod.getReturnType()); 41 smethod.invoke(instance, gresult); 42 43 } 44 return instance; 45 } 46 }
结果: