Search code examples
javaminecraftbukkit

How to run a method from another class but the class is a string


So I have a bunch of classes in my project. One of them is called CommandManger, command, create. The CommandManger is accessing a void method(run) in command.java I also have a method in create.java called run I'm trying to use the run method from create inside the run method in command.

public void run(CommandSender sender, String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    String className = args[0];
    Object c = Class.forName(className).newInstance();
    ArrayList<String> a = new ArrayList<String>(Arrays.asList(args));
    a.remove(0);
    c.run(sender, a.toArray(new String[a.size()]));
}

This is the run method in command. It's being sent a player(sender) the array of strings. Because of the measures in place in the CommandManger there will always be a correct amount of arguments and the first argument will always have a class to reference. However what I have here may not be totally correct. What I am trying to do is create and instance of the create class inside of the method. In this case args[0] is the String "create" the argument after it is the parameter I need to send to the run method in the create class. That's what this is:

ArrayList<String> a = new ArrayList<String>(Arrays.asList(args));
a.remove(0);
c.run(sender, a.toArray(new String[a.size()]));

The problem I am running into here is the run method is not recognized. But It is in every class that will be called from this method.


Solution

  • You used reflection to create object, so you should use reflection to call it method:

    Class<?> cl = Class.forName(className);
    Object c = cl.newInstance();
    String[] params = a.toArray(new String[a.size()]);
    Method method = cl.getDeclaredMethod("run", CommandSender.class, params.getClass());
    method.invoke(c, new Object[] {sender, params});
    

    Or you can use 1 interface for all your class, then cast Object c to that interface.