使用getDeclaredMethod获取任何超级(父)类的私有方法

时间:2015-08-14 14:13:53

标签: java reflection

我需要通过反射调用私有方法。如果私有方法是指定类或超类的一部分,我不会提前知道。我有私有方法的名称,它们的参数和参数类型。 我的第一个方法如下:

Object classToTest = ....;
ArrayList<Method> methods = new ArrayList<Method>();
Class<?> classIndex = classToTest.getClass();

//iterate over (super) classes to collect all methods
do{
    methods.addAll(Arrays.asList(classIndex.getDeclaredMethods()));
    classIndex = classIndex.getSuperclass();
}
while(classIndex.getClass()!=null);

for(Method method : methods){
 //match the right method
}
//call it
method.setAccessible(true);
method.invoke(classToTest,parameterValues);

该方法的问题:从.getDeclaredMethod(...)的源代码显示,从列表中获取正确的方法并非易事。不幸的是,使用了许多私人内部方法,因此无法重复使用......

第二种方法是使用getDeclaredMethod()为我做匹配:

Method method=null;
Class<?> classIndex = classToTest.getClass();

//iterate over (super) classes since private method may be inherited
do{
    //exception catching as part of the normal code is ugly 
    try{
        method = classIndex.getDeclaredMethod(nameOfMethod, parameterTypes);
        //method found thus exit
        break;
    }
    catch(NoSuchMethodException nsme){
        //method not found thus check super class
        classIndex = classIndex.getSuperclass();
    }
}
while(classIndex!=null);

if(method==null) throw new NoSuchMethodException( classToTest.getClass().getName() + "." + nameOfMethod + Arrays.toString(parameterValues));

//no method matching necessary
method.setAccessible(true);
method.invoke(classToTest,parameterValues);

这种方法的缺点:作为代码流程的一部分,异常捕获是丑陋的 - 但是我目前还没有重新实现Class.java的匹配代码。

那么有没有人看到另一种方法来获得正确的私人方法?

0 个答案:

没有答案