Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection - Object is not an instance of declaring class

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 is not an instance of declaring class' error. Any ideas? Thanks!

Main.java

Class<?> base = Class.forName("server.functions.TestFunction"); Method serverMethod = base.getMethod("execute", HashMap.class); serverMethod.invoke(base, new HashMap<String, String>()); 

TestFunction.java

package server.functions;  import java.util.HashMap; import java.util.Map;  import server.*;  public class TestFunction extends ServerBase {      public String execute(HashMap<String, String> params)     {         return "Test function successfully called";     } } 
like image 751
tier1 Avatar asked Nov 11 '12 22:11

tier1


1 Answers

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>()); 
like image 65
raven1981 Avatar answered Sep 22 '22 15:09

raven1981