日期:2014-05-20  浏览次数:20882 次

关于Method方法访问失败的问题的探究
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 异常

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

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> 不包含在返回数组中。如果该类声明带有相同参数类型的多个公共成员方法,则它们都包含在返回的数组中。