如何使用classLoader从加载的类中调用方法?

时间:2013-09-08 00:01:48

标签: java classloader

这是我使用的代码:

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();

我正在加载的课程是 USAGE ,我要调用的方法是 main(String [] args)

1 个答案:

答案 0 :(得分:3)

您无需致电newInstance()。这样做:

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