Java 反射 API 和调用具有可变数量参数的方法

标签 java reflection methods parameter-passing invoke

当我使用 Java 反射 API 调用一个接受可变数量参数的方法时,我在尝试解决这种情况时遇到了问题。每次我尝试这样做时,我都会收到“NoSuchMethodException”。

我要调用的方法声明:

public void AddShow(String movieName, String cinemaName, String... days) {
}

以及执行调用的方法的代码:

public void Exec(String command){
    try {
        String[] words = command.split(" ");
        String commandName = words[0];
        Class<? extends UserInterface> thisClass = (Class<? extends UserInterface>)getClass();
        Class<String>[] par = new Class[words.length-1];
        String[] params = new String[words.length-1];
        for(int i = 1; i< words.length; i++){
            params[i-1] = words[i];
            try {
                par[i-1] = (Class<String>) Class.forName("java.lang.String");
            } catch (ClassNotFoundException e) {
                System.out.println("If this shows up, something is siriously wrong... Waht have you done?!");
            }
        }
        Method method;
        if(par.length != 0) {
            method = thisClass.getMethod(commandName, par);
            method.invoke(new UserInterface(CinemaDb), (Object[])params);
        } else {
            method = thisClass.getMethod(commandName);
            method.invoke(new UserInterface(CinemaDb));
        }
    } catch (SecurityException e) {
        System.out.println("Security error, sry again.");
    } catch (NoSuchMethodException e) {
        System.out.println("Wrong command, try again (check the parameters)!");
    } catch (IllegalAccessException e) {
        System.out.println("You don't have access rights, try again.");
    } catch (IllegalArgumentException e) {
        System.out.println("Wrong arguments, try again.");
    } catch (InvocationTargetException e) {
        System.out.println("Invocation error, try again.");
    }
}

如果您知道如何更改我的 Exec 方法来解决这个问题,我将不胜感激。

谢谢!

最佳答案

Java 中的可变参数是通过数组实现的,因此参数为 String.class、String.class 和 String[].class

关于Java 反射 API 和调用具有可变数量参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7948249/

相关文章:

java - Dagger 2 - 构造函数注入(inject) - 作用域

c# - 如何使用反射获取 Task<T> 中 T 类型的属性?

c# - C# 中的通用类型构造函数解析,适用于具有通用服务注册的 IoC

javascript - 较短的字符串会导致网页卡住

c# - 派生类中存在重写和隐藏方法。为什么?

java - 在 mysql 中存储时间戳的最佳(性能方面)方式

java - xpath识别动态值传递

java - getActionBar() 抛出空指针错误

reflection - 如何使用反射提取接口(interface)类型名称和包?

c++ - 如何为类的每个实例创建实例特定方法?