package com.shengsiyuan.reflect;import java.lang.reflect.Field;
import java.lang.reflect.Method;public class ReflectTester
{
// 该方法实现对Customer对象的拷贝操作
public Object copy(Object object) throws Exception
{
Class<?> classType = object.getClass(); Object objectCopy = classType.getConstructor(new Class[] {})
.newInstance(new Object[] {}); // 获得对象的所有成员变量 Field[] fields = classType.getDeclaredFields(); for (Field field : fields)
{
String name = field.getName(); String firstLetter = name.substring(0, 1).toUpperCase();// 将属性的首字母转换为大写 String getMethodName = "get" + firstLetter + name.substring(1);
String setMethodName = "set" + firstLetter + name.substring(1); Method getMethod = classType.getMethod(getMethodName,
new Class[] {});
Method setMethod = classType.getMethod(setMethodName,
new Class[] { field.getType() }); Object value = getMethod.invoke(object, new Object[] {}); setMethod.invoke(objectCopy, new Object[] { value }); }
return objectCopy;
} public static void main(String[] args) throws Exception
{
Customer customer = new Customer("Tom", 20);
customer.setId(1L); ReflectTester test = new ReflectTester(); Customer customer2 = (Customer) test.copy(customer); System.out.println(customer2.getId() + "," + customer2.getName() + ","
+ customer2.getAge());
}
}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;
}
}
问题:红的部分是什么意思啊?刚学反射机制的哦。麻烦各位牛人再给我说下里面copy方法的流程。谢谢嘞

解决方案 »

  1.   

    Object value = getMethod.invoke(object, new Object[] {});setMethod.invoke(objectCopy, new Object[] { value });红色部分没显示,是这两行代码
      

  2.   

    Object value = getMethod.invoke(object, new Object[] {});这里的object是你传进来的一个Object类的引用,
    用这个引用去调用getMethod方法,new Object[] {}代表是无参数的。这里的getMethod方法就是Customer
    类里面的get方法。最后value的值分别就是Customer里面的 id,name,age的值。
    setMethod.invoke(objectCopy, new Object[] { value });
    这里面的objectCopy是通过这句话:
     Object objectCopy = classType.getConstructor(new Class[] {}) .newInstance(new Object[] {});所得到的一个副本。也就是调用了Customer的无参构造方法,也就是相当于new 了一个Customer对象。objectCopy 就是Customer对象的一个引用。然后通过setMethod.invoke(objectCopy, new Object[] { value });将value值(也就是之前说的那些私有变量的值)用set方法赋给了新的Customer里面的id,name,age这些变量,从而实现了对象的复制。
      

  3.   

    getMethod和setMethod方法是你得到的Method对象,这样
    Object value =getMethod.invoke(object, new Object[] {});
    就相当于value=object.getXXX();
    而getXXX()就是getMethod
    object为Customer类的实例,inovke()方法相当于调用object相应的方法而new Object[] {}方法的参数
    而这里的空数组表示无参数
    下面的setMethod同理