java反射copy对象实例

package com.age.www;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
class ReflectCopyDemo
{
 public static void main(String[] args)  throws Exception
 {
  
//  System.out.println("Hello World!");
  PersonDemo p=new PersonDemo("Lily",30);
  System.out.println(p.getClass().getDeclaredField("name").isAccessible()); 
  //哪怕对象的原属性为public,其对应的field类对象的所有元素的isAccessible()方法返回值仍然为false。。。。
  
  System.out.println("原对象:"+p);
  CopyObj co=new CopyObj(p);
  Object dstobj=co.copy();
  //***************************
  CopyObj.copy(p);  //使用静态方法直接设定了目标对象的初始值。。。
  
 }
}
//通过Array反射类copy 一个类的对象实例,
class CopyObj
{
 Object obj;
 CopyObj(){
 }
 CopyObj(Object obj){
  this.obj=obj;
 }

 //最好声明一个静态类就不用上面这个构造函数传递copy对象了。直接
 // public static Object (Object obj);--->这个静态方法直接不需要单独构造一个CopyObj对象了。
 //用实例方法,产生对象后调用。非静态方法。
 public Object copy() throws Exception{
 
    Class classtype=obj.getClass();
    Object dstObj=classtype.newInstance();
    
    Field[] fldary=classtype.getDeclaredFields();
    for (Field fld:fldary)
    {
     if (!fld.isAccessible())
     {
      String src=(String)fld.getName();
      String setMethodName="set"+src.substring(0,1).toUpperCase()+src.substring(1);
      String getMethodName="get"+src.substring(0,1).toUpperCase()+src.substring(1);
      Method mget=classtype.getDeclaredMethod(getMethodName,new Class[]{});
      Method mset=classtype.getDeclaredMethod(setMethodName,fld.getType());
      Object value=mget.invoke(obj,new Object[]{});
      mset.invoke(dstObj,value);
      
      //fldary里面的Field成员全部都设定为了private!!
     }
    }
    System.out.println("使用实例对象copy()目标对象:"+dstObj);
    return dstObj;
 }
 
 //用静态方法直接调用。
 public static Object copy(Object obj) throws Exception{
  Class<?> objc=obj.getClass();
  Object dstobj=objc.newInstance();
  Field[] fldAry=objc.getDeclaredFields();
  for(Field fld:fldAry){
   fld.setAccessible(true); //这里是和实例copy()区别的地方。
   fld.set(dstobj, fld.get(obj));  //fld get(源对象)/fld.set(目标对象,value)直接搞定。
   
  }
  System.out.println("使用静态类copy():"+dstobj);
  return dstobj;
 }
 
}
class PersonDemo
{
 private String name;
 private int age;
 PersonDemo(){
 }
 PersonDemo(String name ,int age){
  this.name=name;
  this.age=age;
  }
 public void setName(String name){
  this.name=name;
 }
 public void setAge(int age){
  this.age=age;
 }
 public String getName(){
  return name;
 }
 public int getAge(){
  return age;
 }
 public String toString(){
  return name+"--"+age;
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值