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;
}
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 supplynull
as that first argument. Otherwise you need to supply the instance that you actually want to call the method on: