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

365 Views Asked by At

So, as the title describes, I am in need of help with calling a method from a class to another. So, to explain a bit further: I'm storing classes in a HashSet. Now I'm trying to access a method located in that class chosen in that HashSet, but it rather gives me that error:

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).

Code:

 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();
                }

Thats the getTaskClass method

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;
}
1

There are 1 best solutions below

2
On BEST ANSWER

The first argument to the invoke method is the object instance you want to invoke the method on. If the method is static you can simply supply null as that first argument. Otherwise you need to supply the instance that you actually want to call the method on:

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