反射时Java参数类型不匹配 [英] Java argument type mismatch while reflection

查看:362
本文介绍了反射时Java参数类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行从另一个 jar 加载的某个方法,该方法返回一个整数,然后我想将其返回到另一个类并将其传递给我的逻辑.

I am trying to run some method I load from another jar, that returns an integer, and then I want to return it to another class and pass it to my logic.

我使我的方法加载类非常简单,如下所示:

I made my method loading class pretty simple like this:

public class ModuleLoader {

    private Class<?> cls;

    public void initializeCommandModule(Module m) throws Exception {
        URL url = this.getURL(m.getJar());
        this.cls = this.loadClass(m.getMainClass(), url);
    }

    public int execute(Module m, ArrayList<String> args) throws Exception {
        Method method = this.cls.getDeclaredMethod("execute", ArrayList.class);
        return (int) method.invoke(this.cls.newInstance(), 1);
    }

    public int respond(ArrayList<String> args) throws Exception {
        Method method = this.cls.getDeclaredMethod("response", ArrayList.class);
        return (int) method.invoke(this.cls.newInstance(), 1);
    }

    private Class<?> loadClass(String cls, URL url) throws ClassNotFoundException, IOException {
        URLClassLoader loader = new URLClassLoader(new URL[]{url});
        Class<?> toReturn = loader.loadClass(cls);
        loader.close();

        return toReturn;
    }

    private URL getURL(String jar) throws MalformedURLException {
        return new File(jar).toURI().toURL();
    }

}

看看execute(Module m, ArrayList args)方法,这一行抛出错误:

Take a look at the execute(Module m, ArrayList<String> args) method, this line throws the error:

    return (int) method.invoke(this.cls.newInstance());

我加载的 jar 库如下所示:

The jar library I load looks like this:

public class Test {

    public int execute(ArrayList<String> i) {
        System.out.println("Hello world!");
        return 0;
    }

}

为什么当我运行该方法时会抛出以下异常?

Why when I run that method I get the following exception thrown?

Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at ben.console.modules.ModuleLoader.execute(ModuleLoader.java:24)
    at ben.console.CommandProcessor.process(CommandProcessor.java:37)
    at ben.console.Console.listen(Console.java:25)
    at ben.console.Console.main(Console.java:31)

多谢指教!

推荐答案

您忘记将参数传递给方法调用.

You forgot to pass an argument to your method invocation.

return (int) method.invoke(this.cls.newInstance(), myArrayList);

您也可以使用空参数调用:

You can also invoke with a null argument:

return (int) method.invoke(this.cls.newInstance(), (Object[])null);

这篇关于反射时Java参数类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆