package com.wingsoft;
 
import java.lang.reflect.Method;import cn.com.wingsoft.AccessTest;public class ReflectTechnique { public static void main(String[] args) throws Exception{
AccessTest accessTest = new AccessTest();
    Class clazz = accessTest.getClass();
    Method[] methods = clazz.getMethods();
    for(Method method : methods){
     method.setAccessible(true); 
     method.invoke(accessTest);   
    }
}
}
==================package cn.com.wingsoft;public class AccessTest {
  private void f(){
  System.out.println("function f() !!!");
  }
  protected void g(){
  System.out.println("function g() !!!");
  }
  void h(){
  System.out.println("function h() !!!");
  }

我哪里错了  为何报告异常!!!  坐等大神给予解答
Exception in thread "main" java.lang.reflect.InvocationTargetException
Methods异常

解决方案 »

  1.   

    调之前打印一下方法名就知道了,
    从Object继承来的方法也被调用了,
    有些是要参数的,
    so...
      

  2.   


    public class ReflectTechnique { public static void main(String[] args) throws Exception {
    AccessTest accessTest = new AccessTest();
    Class clazz = accessTest.getClass();
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
    method.setAccessible(true);
    method.invoke(accessTest,null);
    }
    }
    }Method[] methods = clazz.getDeclaredMethods();
    要用这个方法
    public Method[] getDeclaredMethods()
                                throws SecurityException返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。返回数组中的元素没有排序,也没有任何特定的顺序。如果该类或接口不声明任何方法,或者此 Class 对象表示一个基本类型、一个数组类或 void,则此方法返回一个长度为 0 的数组。类初始化方法 <clinit> 不包含在返回数组中。如果该类声明带有相同参数类型的多个公共成员方法,则它们都包含在返回的数组中。 
    public Method[] getMethods()
                        throws SecurityException返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。数组类返回从 Object 类继承的所有(公共)member 方法。返回数组中的元素没有排序,也没有任何特定的顺序。如果此 Class 对象表示没有公共成员方法的类或接口,或者表示一个基本类型或 void,则此方法返回长度为 0 的数组。