java - Storing Class in Array -
i have n class (class1, class2, .., classn), each have static main methods.
i wish store class in array, , call main method once each class. type have declare array?
this have done according reply t.j. crowder
arraylist<class> meoa = new arraylist( arrays.aslist(class.forname("mypackage.class1"), class.forname("mypackage.class2"), class.forname("mypackage.class3"), class.forname("mypackage.class4"), class.forname("mypackage.class5"))); for(class cls:meoa) { system.out.println("invoking:"+cls.getname()); method m = cls.getdeclaredmethod("main", string[].class); object[] arg = new object[1]; arg[0] = new string[] {}; m.invoke(null, arg); }
the type class[]
(array of class
). (since main
static method, can't use interface this.)
when you're ready call main
, you'd via reflection, e.g.:
class[] classes = /*...create , fill in array...*/; (class cls : classes) { // main method accepting array of strings method m = cls.getdeclaredmethod("main", string[].class); m.invoke(null, /*...see note below...*/); }
re "see note below" above: argument pass invoke
object[]
(array of object
) containing arguments give main
. since main
expects single argument (an array of strings), have pass single-entry object[]
1 entry string[]
. instance, if going pass ["one", "two", "three"]
main
, you'd construct invoke
argument this:
object[] arg = new object[1]; // room 1 argument arg[0] = new string[] { "one", "two", "three" }; // 1 arg string array m.invoke(null, arg); // invoke main
(the null
in call invoke
instance on call method; since main
static, supply null
that.)
Comments
Post a Comment