package cn.tzz.java.reflect;
2.
3.import cn.tzz.aop.entity.Person;
4.import java.lang.reflect.Field;
5.import java.lang.reflect.Method;
6.import org.junit.Test;
7.
8.public class TestReflect {
9.
10. /** 方法--属性复制 */
11. public void fieldCopy(Object source, Object target) throws Exception {
12. Method[] methods = source.getClass().getDeclaredMethods();
13. for (Method method : methods) {
14. String methodName = method.getName();
15. System.out.println(methodName);
16. if (methodName.startsWith("get")) {
17. Object value = method.invoke(source, new Object[0]);
18. System.out.println(value);
19. String setMethodName = methodName.replaceFirst("(get)", "set");
20. Method setMethod = Person.class.getMethod(setMethodName,
21. method.getReturnType());
22. setMethod.invoke(target, value);
23. }
24. }
25. }
26.
27. /** 属性字段名、值、数据类型 */
28. public void getFields(Object object) throws Exception {
29. Field[] fields = object.getClass().getDeclaredFields();
30. for (Field field : fields) {
31. field.setAccessible(true);
32. String classType = field.getType().toString();
33. int lastIndex = classType.lastIndexOf(".");
34. classType = classType.substring(lastIndex + 1);
35. System.out.println("fieldName:" + field.getName() + ",type:"
36. + classType + ",value:" + field.get(object));
37. }
38. }
39.
40. @Test
41. public void test() throws Exception {
42. Person person = new Person();
43. person.setId(1L);
44. person.setName("AAA");
45. Person person2 = new Person();
46. fieldCopy(person, person2);
47. getFields(person2);
48. }
49.}
java的反射
猜你喜欢
转载自weitao1026.iteye.com/blog/2266133
今日推荐
周排行