2011-03-02 用反射的方式获取父类中的所有属性和方法 博客分类: 反射 JDBCjunit Java 代码 1. package com.syh.jdbc.reflection_super; 2. 3. /** 4. * 父类 5. * @author syh 6. * 7. */ 8. 9. public class Parent { 10. 11. public String publicField = "1"; 12. 13. String defaultField = "2"; 14. 15. protected String protectedField = "3"; 16. 17. private String privateField = "4" ; 18. 19. public void publicMethod() { 20. System.out.println("publicMethod..."); 21. } 22. 23. void defaultMethod() { 24. System.out.println("defaultMethod..."); 25. } 26. 27. protected void protectedMethod() { 28. System.out.println("protectedMethod..."); 29. } 30. 31. private void privateMethod() { 32. System.out.println("privateMethod..."); 33. } 34. 35.} Java 代码 1. package com.syh.jdbc.reflection_super; 2. 3. /** 4. * 子类 5. * @author syh 6. * 7. */ 8. 9. public class Son extends Parent{ 10. 11.} Java 代码 1. package com.syh.jdbc.reflection_super; 2. 3. import java.lang.reflect.Field; 4. 5. import java.lang.reflect.InvocationTargetException; 6. import java.lang.reflect.Method; 7. 8. /** 9. * 方法类 10. * @author syh 11. * 12. */ 13. 14.public class ReflectionUtils { 15. 16. /** 17. * 循环向上转型, 获取对象的 DeclaredMethod 18. * @param object : 子类对象 19. * @param methodName : 父类中的方法名 20. * @param parameterTypes : 父类中的方法参数类型 21. * @return 父类中的方法对象 22. */ 23. 24. public static Method getDeclaredMethod(Object object, String methodName, Class> ... parameterTypes){ 25. Method method = null ; 26. 27. for(Class> clazz = object.getClass() ; clazz != Object.class ; clazz = clazz.getSuperclass()) { 28. try { 29. method = clazz.getDeclaredMethod(methodName, parameterTypes) ; 30. return method ; 31. } catch (Exception e) { 32. ...