您的位置:首页 > 编程语言 > Java开发

java反射(5)通过反射拷贝对象

2017-10-14 10:38 555 查看
本篇就是反射的基本应用 

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

}


如果对您有帮助 记得帮博主刷个赞或是评论哦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 语言 反射