使用 getMethod 从另一个 class 调用方法会出错

Calling a method from another class with the getMethod gives an error

因此,正如标题所述,我需要帮助从 class 调用方法到另一个。因此,进一步解释一下:我将 classes 存储在 HashSet 中。现在我正在尝试访问位于 HashSet 中选择的 class 中的方法,但它给了我错误:

java.lang.IllegalArgumentException: object is not an instance of declaring class
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).

代码:

 Class<Task> neededClass = taskHandler.getTaskClass("NodeMovementTask");
                try {
                    neededClass.getMethod("addToQueue", Timeline.class, int.class).invoke(timeline, cycleCount);
                } catch (IllegalAccessException | IllegalArgumentException
                        | InvocationTargetException | NoSuchMethodException
                        | SecurityException e) {
                    e.printStackTrace();
                }

这就是 getTaskClass 方法

public Class<Task> getTaskClass(String classToSearch) {
    Class<Task> returningClass = null;
    for(Class<Task> foundClass : tasks) {
        if(foundClass.getName().equalsIgnoreCase("packages." + classToSearch)) {
            System.out.println("Found!");
            return returningClass = foundClass;
        }
    }
    return returningClass;
}

invoke 方法的第一个参数是您要调用该方法的对象实例。如果该方法是静态的,您可以简单地提供 null 作为第一个参数。否则,您需要提供您实际想要调用该方法的实例:

neededClass.getMethod("addToQueue", Timeline.class, int.class)
     .invoke(instance, timeline, cycleCount);
             ^^^^^^^^