Java Reflection - Object is not an instance of declaring class
Solution 1:
You're invoking the method with the class, but you need an instance of it. Try this:
serverMethod.invoke(base.newInstance(), new HashMap<String, String>());
Solution 2:
You are trying to invoke the execute
method on the object base
, which is actually a Class
object returned by your Class.forName()
call.
This would work for a static
(class) method - but execute
is a non-static (instance) method.
(It would also work for calling an instance method of an object of type Class
- but that's not what you are trying to achieve here!)
You need an actual instance of TestFunction
to invoke the method on, or you need to make the method static
.
When invoking a static method by reflection, the first argument to invoke()
is ignored, so it is conventional to set it to null
, which clarifies the fact that there's no instance involved.
Although your current example method would do the same thing for any TestFunction
object, in general an instance method could produce a different result for each object - so the .invoke()
reflection method needs to know which object to run the method on.