vendredi 24 avril 2020

How to call main method on class identified by String

I'm trying to call the main method on a Java class identified by a String. In the actual program, the class identifier will be a variable, but for the moment I'm trying this:

try {       
    Class c = Class.forName("Arena");

    Class[] aarg = new Class[1];  
    aarg[0] = String[].class;

    Method m = c.getMethod("main", aarg); // Needs parameter class list
    m.invoke(newargs);
}           
catch (Exception e) {
    System.err.println(e);      
}

First, I get a compiler warning (Athena is the name of the class I'm currently working in):

Note: Athena.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Then on testing I get this exception:

java.lang.IllegalArgumentException: wrong number of arguments

I feel like the primary thing is I don't know how to identify the parameter of main() as an array of the String class (failed to find an example of that), but maybe I'm missing more than that.





Aucun commentaire:

Enregistrer un commentaire