简体   繁体   中英

How to call a method from loaded class using classLoader?

This is the code I use :

File urlclasspath = new File("C:/Users/ASUS/Desktop/semantics/semantics/bin");
            URL urlarray[] = new URL[1];
            urlarray[0] = urlclasspath.toURI().toURL();

            MyClassLoader mycl = new MyClassLoader(urlarray);

            Class myclass = mycl.loadClass("USAGE");

            Object obj = myclass.newInstance();

And the class I'm loading is USAGE and the method I want to call is main(String[] args)

You don't need to call newInstance() . Do this:

Class<?> myclass = mycl.loadClass("USAGE"); // get the class
Method m = myclass.getMethod("main", String[].class); // get the method you want to call
String[] args = new String[0]; // the arguments. Change this if you want to pass different args
m.invoke(null, args);  // invoke the method

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