简体   繁体   中英

Java Reflection Enumerate Type in GetMethod

I'm trying to call a method by name at runtime with reflection. But I need to make this compatible with all methods.

I'll explain:

I have a text with this current format: methodname|param1;param2;etc...

Now i want this text split, and find the method in my class.

    try {
      String methodName = message.substring(0,message.indexOf("|"));
      method = ServerManager.class.getMethod(methodName, HERE I DONT KNOW WHAT TO PUT);

      //This code not tested yet//
      if(method != null)
      {
        method.invoke(ServerManager.class,message.split("|")[1].split(";"));
      }
    }
    catch (NoSuchMethodException e) { e.printStackTrace(); }

To find the method, I need to put the type. But number of parameters and the name of the method change. How can I give to getMethod an array of my parameters type?

I've tryied to enumerate all getClass() of each parameters but getMethod seems not accepting array in second parameters.

Sorry for my bad english, and thank you for help.

Remove the class.getClass() and then you can pass an array of Class , for instance:

method = ServerManager.class
                      .getMethod(methodName, new Class[]{Integer.class, String.class});

or simply:

ServerManager.class.getMethod(methodName, Integer.class, String.class);

the array will be implicitly added there by Java compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM