结合本网站和许多其他网站上许多帖子的信息,我得到了以下代码,用于动态添加(在运行时)一个包含类的目录到类路径,并在该目录中加载一个类。
我正在使用 OSGi 包并从 eclipse 运行“Eclipse 应用程序”(一种运行配置)。
这是我正在使用的代码:
案例 1:(两种情况都是不同的事情,我尝试做同样的事情。)
File file = new File("/Users/alek/fastFIX/myJPass/");
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("GuiLauncher"); //the file GuiLauncher.class is in the /Users/alek/fastFIX/myJPass/ directory
Class[] argTypes = new Class[] { String[].class };
Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class
main.invoke(null, (Object) args);
我没有收到任何错误,也没有任何反应。 我还尝试了以下内容,因为我实际上需要加载的类与其他(已加载的)类进行交互。
案例 2:
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new File("/Users/alek/fastFIX/myJPass/").toURL() }, currentThreadClassLoader);
Thread.currentThread().setContextClassLoader(urlClassLoader);
然后我这样加载:
Class<?> c = Class.forName("GuiLauncher");
或者像这样:
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass("GuiLauncher");
并尝试像这样调用主函数:
Class[] argTypes = new Class[] { String[].class };
Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class
main.invoke(null, (Object) args);
这里也没有任何反应。
有什么可能发生的线索吗?我已经阅读了这里和其他许多地方的所有相关帖子,但没有运气。
最佳答案
在 OSGI 框架中,有必要将 OSGI 类加载器添加为父级,如下所示: ... ClassLoader cl = new URLClassLoader(new URL[]{file.toURI().toURL()}, this.getClass().getClassLoader()); ...
关于java - 使用 Eclipse 和 OSGi 将类动态加载到 Java 类路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12714368/