反射学习

package com.xuli.test8;

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

import com.xuli.test5.test1;

public class Test1
{
	public Object copy(Object object) throws Exception
	{
		Class<?> classtype = object.getClass();
		//
		// //方法一 获取类的实例 只能获取不带参数的的类的实例
		//
		// Object object2 = class1.newInstance();
		//
		// System.out.println(object2);

		// 方法二 获取类的实例 利用构造函数

		Constructor<?> constructor = classtype.getConstructor(new Class[] {});

		Object object2 = constructor.newInstance(new Object[] {});// 获取constructor的一个实例

		// 接下来获取属性的实例

		Field[] fields = classtype.getDeclaredFields();

		for (Field field : fields)
		{
			// System.out.println(field);
			String name = field.getName();

			// System.out.println(name);

			String firstLetter = name.substring(0, 1).toUpperCase();

			// System.out.println(firstLetter);

			String getMethodname = "get" + firstLetter + name.substring(1);

			// System.out.println(getMethodname);

			String setMethodname = "set" + firstLetter + name.substring(1);

			// System.out.println(setMethodname);

			Method getMethod = classtype.getMethod(getMethodname,
					new Class[] {});

			Method setMethod = classtype.getDeclaredMethod(setMethodname,
					field.getType());

			Object value = getMethod.invoke(object, new Object[] {});

			Object vaule1 = setMethod.invoke(object2, new Object[] { value });

		}

		return object2;
	}

	public static void main(String[] args) throws Exception
	{
		Customer customer = new Customer("Tom", 20);

		customer.setId(10L);

		Test1 test1 = new Test1();

		Customer customer2 = (Customer) test1.copy(customer);

		System.out.println(customer2);

	}
}

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

}

用反射复制

代码如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xulimessage

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值