How to call a method from loaded class using classLoader?

删除回忆录丶 提交于 2019-12-23 15:29:54

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/18679087/how-to-call-a-method-from-loaded-class-using-classloader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!