问题描述
在我目前的项目中,我觉得有必要使用反射在Java中创建一种模拟回调系统。但是,我遇到了让我的反思真正起作用的问题。错误的代码如下:
On my current project, I've felt the need to create a sort of simulated callback system in Java using reflection. However, I'm having issues getting my reflection to actually function. The code at fault follows:
public Callback(Object parentObj, String methodName, Class<?>...parameters)
{
if(parentObj == null)
throw new IllegalArgumentException("parentObj cannot be null", new NullPointerException());
Class<?> clazz = parentObj.getClass();
// Trace debugging, see output
for(Method m : clazz.getDeclaredMethods())
if(m.getName().equals("myMethod")) System.out.println (m);
try { this.method = clazz.getMethod(methodName, parameters); }
catch(NoSuchMethodException nsme) { nsme.printStackTrace(); } // Exception caught
catch(SecurityException se) { se.printStackTrace(); }
this.parentObj = parentObj;
this.parameters = parameters;
}
当我构建回调
对象,我正在使用这样的语法:
When I construct the Callback
object, I'm using syntax like this:
new Callback(this, "myMethod", boolean.class)
当我尝试创建我的伪回调时,它会遇到 NoSuchMethodException
catch block。我在上面包含了一些跟踪调试,以显示我的一个方法的输出失败。输出:
When I try to create my pseudo-callback, it hits the NoSuchMethodException
catch block. I've included some trace debugging above to show the output of one of my methods failing. The output:
private void my.package.MyClass.myMethod(boolean)
java.lang.NoSuchMethodException: my.package.MyClass.myMethod(boolean)
at java.lang.Class.getMethod(Class.java:1605)
at my.package.other.Callback.<init>(Callback.java:63)
我无法解决问题,所以我开始打猎,但收效甚微。我能找到的最好的是提到编译的JAR和运行时之间的版本冲突。但是, MyJar.jar / META-INF / MANIFEST.MF
包含创建者:1.6.0_02(Sun Microsystems Inc.)
。我的IDE正在运行 C:\Program Files \ Java \ jdk1.6.0_02 \bin\javac.exe
来编译我的项目。我正在使用 C:\Program Files \Java \ jdk1.6.0_02 \bin\java.exe
来运行我的JAR。
I couldn't figure the problem out, so I started hunting, to little avail. The best I could find was mention of versioning conflict between the compiled JAR and the runtime. However, MyJar.jar/META-INF/MANIFEST.MF
contains Created-By: 1.6.0_02 (Sun Microsystems Inc.)
. My IDE is running C:\Program Files\Java\jdk1.6.0_02\bin\javac.exe
to compile my project. I'm using C:\Program Files\Java\jdk1.6.0_02\bin\java.exe
to run my JAR.
我很遗憾为什么 Class.getMethod
声称该方法不存在,但是 Class .getMethods
似乎没有问题找到它。救命? :(
I'm at a loss why Class.getMethod
is claiming the method doesn't exist, but Class.getMethods
seems to have no problem finding it. Help? :(
推荐答案
您的方法是私有的,但 getMethod()
仅返回公共方法。
Your method is private but getMethod()
only returns public method.
您需要使用 getDeclaredMethod()
。
这篇关于Java:当方法明显存在时,NoSuchMethodException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!