1. import java.lang.reflect.Method;
    2. class Moo {
    3. private void doSth1(){
    4. System.out.println("私有方法的调用");
    5. }
    6. protected void doSth2(){}
    7. void doSth3(){}
    8. public void doSth4(){}
    9. }
    10. public class ShowMethods2 {
    11. public static void main(String[] args) throws Exception{
    12. Class<?> c = Class.forName("com.thinking.in.java.course.chapter14.two.Moo");
    13. final Object o = c.newInstance();
    14. //c.getMethods()拿到该类体系的所有public方法
    15. for (Method method : c.getMethods()) {
    16. //System.out.println(method.toString());
    17. }
    18. //只能拿到本类的所有方法
    19. for (Method declaredMethod : c.getDeclaredMethods()) {
    20. System.out.println(declaredMethod.toString());
    21. if(declaredMethod.toString().contains("doSth1")){
    22. declaredMethod.setAccessible(true);
    23. declaredMethod.invoke(o);
    24. }
    25. }
    26. }
    27. }