cgameing cgameing - 4 months ago 10x
Java Question

Java - How to invoke a method from another class, with the class name and method name as a string

This method is called regularly

public static void stynax(String N[]) {
if (N[1].equals("echo")) { echo.s(); main(); }
if (N[1].equals("detectos")) { detectos.s(); main(); }
if (N[1].equals("getuser")) { getuser.s(); main(); }
if (N[1].equals("exit")) { exit.s(); main(); }
if (N[1].equals("makefile")) { makefile.s(); main(); }
if (N[1].equals("cd")) { cd.s(); main(); }
if (N[1].equals("system")) { system.s(); main(); }

How can I invoke all these methods


Ect, by seeing if the class exists, then calling the corresponding method.
N[1] is always the class name. The class where this method is stored is in a class called main, and the classes that are called are in a different package called Commands.

I always seem to get this error, when trying to make a Class variable, i think this is the main issue.


So it never gets to invoke the method.

To simplify.

1) The program gets the class name as a String as N[1]

2) It sees if the class exists

3) If the class exists it calls it by the name of the class N[1].s();

Edit: Imports used
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

import cgameing.Commands.FileBrowser;
import cgameing.Commands.banner;
import cgameing.Commands.detectos;
import cgameing.Commands.echo;
import cgameing.Commands.exit;
import cgameing.Commands.getuser;
import cgameing.Commands.makefile;
import cgameing.Commands.system;

end of edit:

This one works, for anyone wanting to do the same thing

(Class.forName("commands."+N[1])).getDeclaredMethod("s", null).invoke(null,null);

Thanks everyone


You'll need to use reflection. Try something as follows. Use fully qualified class name instead of "XYZ" if your class is in a different package.

import java.lang.reflect.*;
import java.lang.*;

public class ReflectionTest {
 public static void main(String[] args)throws NoSuchMethodException,
 InvocationTargetException {
  (Class.forName("XYZ")).getDeclaredMethod("ABC", null).invoke(null,null);

class XYZ
  public static void ABC()

For your use case given your classes are in commands package (as you stated in a comment). The fully qualified name will then be commands.classname

(Class.forName("commands."+N[1])).getDeclaredMethod("s", null).invoke(null,null);