本文介绍了Java:当方法明确存在时,NoSuchMethodException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的项目中,我觉得需要使用反射在 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;
}

当我构造 Callback 对象时,我使用这样的语法:

When I construct the Callback object, I'm using syntax like this:

new Callback(this, "myMethod", boolean.class)

当我尝试创建我的伪回调时,它遇到了 NoSuchMethodException 捕获块.我在上面包含了一些跟踪调试来显示我的一种方法失败的输出.输出:

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 包含 Created-By: 1.6.0_02 (Sun Microsystems Inc.).我的 IDE 正在运行 C:Program FilesJavajdk1.6.0_02injavac.exe 来编译我的项目.我正在使用 C:Program FilesJavajdk1.6.0_02injava.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 FilesJavajdk1.6.0_02injavac.exe to compile my project. I'm using C:Program FilesJavajdk1.6.0_02injava.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 03:15