Java Reflection - Object is not an instance of declaring class

后端 未结 2 2008
离开以前
离开以前 2020-12-16 08:54

This question is being asked everywhere on Google but I\'m still having trouble with it. Here is what I\'m trying to do. So like my title states, I\'m getting an \'object

相关标签:
2条回答
  • 2020-12-16 09:45

    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>());
    
    0 讨论(0)
  • 2020-12-16 09:57

    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.

    0 讨论(0)
提交回复
热议问题