• 2018.5.11 Java利用反射实现对象克隆


    package com.lanqiao.demo;
    
    /**
     * 创建人
     * @author qichunlin
     *
     */
    public class Person {
    	private int id;
    	private String name;
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	
    	//有参构造方法
    	public Person(String name,int id) {
    		super();
    		this.id = id;
    		this.name = name;
    	}
    	
    	//无参构造方法
    	public Person() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    	
    	
    }
    
    package com.lanqiao.demo;
    /**
     * 复制对象
     * @author qichunlin
     *
     */
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    public class ReflectPerson {
    	public Object copy(Object object) throws Exception{
    		//加载类
    		Class c = object.getClass();
    		//获取类中的构造方法
    		Constructor ct = c.getConstructor(new Class[] {});
    		//在构造方法中传值
    		Object obj = ct.newInstance(new Object[] {});
    		
    		
    		//获取所有  属性  返回数组
    		Field[] f = c.getDeclaredFields();
    		for(Field field : f) {
    			String name = field.getName();
    			//System.out.println("a"+name);
    			//截取
    			String firstLetter = name.substring(0, 1).toUpperCase();
    			String getMethodName = "get"+firstLetter+name.substring(1);
    			String setMethodName = "set"+firstLetter+name.substring(1);
    			//获取无参构造方法
    			Method getMethod = c.getMethod(getMethodName, new Class[] {});
    			Method setMethod = c.getMethod(setMethodName, new Class[] {field.getType()});
    			//执行赋值无参构造方法
    			Object value = getMethod.invoke(object, new Object[] {});
    			System.out.println(value);
    			//执行赋值有参构造方法
    			setMethod.invoke(obj, new Object[] {value});
    		}
    		
    		return obj;
    		
    	}
    	
    }
    
    
    package com.lanqiao.demo;
    
    import java.lang.reflect.InvocationTargetException;
    
    /**
     * @author qichunlin
     *
     */
    public class Test {
    	public static void main(String[] args) throws Exception,InvocationTargetException{
    		ReflectPerson rp = new ReflectPerson();
    		Person p = new Person("Legend",22);
    		Person obj = (Person)rp.copy(p);
    		System.out.println(obj.getName()+"	"+obj.getId());
    	}
    	
    }
    
  • 相关阅读:
    LeetCode90.子集 ||
    Ubuntu下的Matlab安装
    FAQ
    青石板
    交叉熵损失函数
    tf常用函数
    激活函数
    SGD和GD的区别
    卷积神经网络
    Ubuntu安装Matlab2016b
  • 原文地址:https://www.cnblogs.com/qichunlin/p/8992978.html
Copyright © 2020-2023  润新知