18. // 获得和属性对应的 getXXX()方法的名字
19.
String getMethodName = "get" + firstLetter + fieldNam
e.substring(
1
);
20. // 获得和属性对应的 setXXX()方法的名字
21.
String setMethodName = "set" + firstLetter + fieldNam
e.substring(
1
);
22.
23. // 获得和属性对应的 getXXX()方法
24.
Method getMethod = classType.getMethod(getMethodN
ame, new Class[] {});
25. // 获得和属性对应的 setXXX()方法
26. Method setMethod = classType.getMethod(setMethodN
ame, new Class[] { field.getType() });
27.
28. // 调用原对象的 getXXX()方法
29.
Object value = getMethod.invoke(object, new Object[] {
});
30. System.out.println(fieldName + ":" + value);
31. // 调用拷贝对象的 setXXX()方法
32. setMethod.invoke(objectCopy, new Object[] { value });
33. }
34.
return objectCopy;
35. }
36.
37. public static void main(String[] args) throws Exception {
38.
Customer customer = new Customer("Tom",
21
);
39.
customer.setId(new Long(
1
));
40.
41. Customer customerCopy = (Customer) new ReflectTester(
).copy(customer);
42. System.out.println("Copy information:" + customerCopy.g
etId() + " "
43. + customerCopy.getName() + " " + customerCopy.g
etAge());
44. }
45. }
46.
47. class Customer {
48. private Long id;
49.
50. private String name;
51.
52. private int age;