JavaSE 反射 (进阶)

本文介绍了一个使用Java反射机制复制对象实例的方法。通过反射获取目标类的方法并调用这些方法来创建一个新对象,并将源对象的数据复制到新对象中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



package com.java.reflection;

import java.lang.reflect.Method;

public class ReflectTest {

	public Object copyInstance(Object o) throws Exception {
//		Class<?> classType = Class.forName("com.java.reflection.Customer");	
		Class<?> classType=o.getClass(); // 第三种获取Class对象的方式.

		Method methodOfName = classType.getMethod("getName");
		Method methodOfId = classType.getMethod("getId");
		Method methodOfAge = classType.getMethod("getAge");

		Object customer2 = classType.newInstance();

		Object name = methodOfName.invoke(o);
		Object id = methodOfId.invoke(o);
		Object age = methodOfAge.invoke(o);

		Method setMethodOfName = classType.getMethod("setName",
				new Class[] { String.class });
		Method setMethodOfId = classType.getMethod("setId",
				new Class[] { Long.class });
		Method setMethodOfAge = classType.getMethod("setAge",
				new Class[] { int.class });

		setMethodOfName.invoke(customer2, name);
		setMethodOfId.invoke(customer2, id);
		setMethodOfAge.invoke(customer2, age);

		return customer2;

	}

	public static void main(String[] args) throws Exception {
		ReflectTest test = new ReflectTest();
		Customer customer1 = new Customer("PresidentXi", Long.valueOf(1000010),
				65);
//		Object customer2 = new Customer();

		Object customer2 = test.copyInstance(customer1);
		System.out.println(customer2.toString());

	}

}

class Customer {
	private String name;
	private Long id;
	private int age;

	public Customer() {

	}

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

	public String getName() {
		return name;
	}

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

	public Long getId() {
		return id;
	}

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

	public int getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "name is: " + name + " age is " + age + " id number is " + id;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值