本篇就是反射的基本应用
public class CopyObj {
public static void main(String[] args) throws Exception {
Person p=new Person();
p.setAddress("北京");
p.setId(1);
p.setName("张三丰");
Object obj=copyObject(p);
System.out.println(obj);
}
public static Object copyObject(Object obj) throws Exception {
//获得传递过来对象的方法和属性
Class<? extends Object> class1 = obj.getClass();
Field[] fields = class1.getDeclaredFields();
Constructor<? extends Object> constructor =class1.getDeclaredConstructor(new Class[] {});
//创建一个对象
Object instance =constructor.newInstance(new Object[] {});
for(Field f:fields) {
//获得name
String fname=f.getName();
//获得属性类型
Class<?> type = f.getType();
//获得属性对应的set方法
String setMethodName ="set"+fname.substring(0,1).toUpperCase()+fname.substring(1);
String getMethodName ="get"+fname.substring(0,1).toUpperCase()+fname.substring(1);
//获得get方法
Method gmthod =class1.getDeclaredMethod(getMethodName, null);
Object gresult=gmthod.invoke(obj, null);
Method smethod = class1.getDeclaredMethod(setMethodName, new Class[] {gmthod.getReturnType()});
smethod.invoke(instance, new Object[] {gresult});
}
return instance;
}
}
如果对您有帮助 记得帮博主刷个赞或是评论哦