java se 学习笔记 之 reflection(完成一个对象copy的demo)4

package com.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTester {

	public static void main(String [] args)throws Exception{
		ReflectTester reflect = new ReflectTester();
		Customer customer = new Customer();
		customer.setId(1L);
		customer.setAge(20);
		customer.setName("张三");
		Customer customer2 = (Customer)reflect.copy(customer);
		System.out.println(customer2.getId()+" "+customer2.getName()+" , "+customer2.getAge());
	}
	//该方法实现对Customer对象的拷贝操作
	public Object copy(Object object) throws Exception{
		//得到操作类的Class对象的第三种方式
		Class<?> classType = object.getClass();
		
		//获得操作类的Constructor对象
		Constructor cons = classType.getConstructor(new Class[]{});
		//用操作类对象的构造方法对象来new出一个操作类的对象。
		Object obj = cons.newInstance(new Object[]{});
		
		//得到类对象中声明的所有的成员变量
		Field[] fields = classType.getDeclaredFields();
		for(Field field:fields){
			//得到成员变量的名称
			String name = field.getName();
			
			//截取成员变量的第一个字母,并设置成大写字母
			String firstLetter = name.substring(0,1).toUpperCase();//将属性的首字母转换为答大写。
			//拼凑getter方法的方法名
			String getMethodName = "get"+firstLetter+name.substring(1);
			//拼凑setter方法的方法名
			String setMethodName = "set"+firstLetter+name.substring(1);
			//根据getter的方法名利用反射机制得到Class类对象中的方法对象
			Method getMethod = classType.getMethod(getMethodName, new Class[]{});
			//根据setter的方法名利用反射机制得到Class类对象中的方法对象
			Method setMethod = classType.getMethod(setMethodName, new Class[]{field.getType()});
			//执行getter方法(调用个getter方法的对象是object)
			Object value = getMethod.invoke(object, new Object[]{});
			//执行setter方法(将object对象中的value值,设置到obj对象中,完成拷贝)
			setMethod.invoke(obj, new Object[]{value});
		}
		//System.out.println(classType.getName());
		System.out.println(obj);
		return obj;
	}
}


class Customer{
	private Long id;
	
	private String name;
	
	private int age;
	
	public Customer(){
		
	}
	
	public Customer(String name,int age){
		this.name  = name;
		this.age = age;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值