Java 使用getDeclaredMethod获取任何超级(父)类的私有方法
我需要通过反射调用一个私有方法。事先我不知道这个私有方法是指定类的一部分还是超类的一部分。我有私有方法的名称、它们的参数和参数类型。 我的第一个方法是:Java 使用getDeclaredMethod获取任何超级(父)类的私有方法,java,reflection,Java,Reflection,我需要通过反射调用一个私有方法。事先我不知道这个私有方法是指定类的一部分还是超类的一部分。我有私有方法的名称、它们的参数和参数类型。 我的第一个方法是: Object classToTest = ....; ArrayList<Method> methods = new ArrayList<Method>(); Class<?> classIndex = classToTest.getClass(); //iterate over (super) class
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);
objectclasstotest=。。。。;
ArrayList方法=新的ArrayList();
类classIndex=classToTest.getClass();
//迭代(超级)类以收集所有方法
做{
addAll(Arrays.asList(classIndex.getDeclaredMethods());
classIndex=classIndex.getSuperclass();
}
while(classIndex.getClass()!=null);
用于(方法:方法){
//匹配正确的方法
}
//叫它
方法setAccessible(true);
调用(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);
Method=null;
类classIndex=classToTest.getClass();
//迭代(超级)类,因为私有方法可能被继承
做{
//异常捕获作为普通代码的一部分是丑陋的
试一试{
方法=classIndex.getDeclaredMethod(方法名称,参数类型);
//找到的方法因此退出
打破
}
捕获(NoSuchMethodException nsme){
//未找到方法,因此请检查超类
classIndex=classIndex.getSuperclass();
}
}
while(classIndex!=null);
如果(method==null)抛出新的NoSuchMethodException(classToTest.getClass().getName()+““+nameOfMethod+Arrays.toString(parameterValues));
//不需要方法匹配
方法setAccessible(true);
调用(classToTest,parameterValues);
这种方法的缺点:作为代码流的一部分捕获异常是丑陋的-但是,如果不重新实现Class.java的匹配代码,我目前看不到替代方法
那么有没有人找到了另一种方法来获得正确的私有方法?您如何确定要寻找的方法?你有关于方法签名的哪些信息?也许你可以用
lookupMethod()
函数包装你的例子来显示你的搜索参数。我有方法的名称和参数+它们的类型。我认为第二种方法是正确的,让标准库进行匹配。不幸的是,Java坚持在有人打喷嚏时抛出异常,而不是返回null,这在本例中是完美的。但事实就是这样。IMO您可以将该方法与其类缓存在一起,这样可以提供良好的性能……这在频繁调用getDeclaredMethod时是很糟糕的