我正在尝试做并且已经研究了很多天的方法是让一个母 jar 浏览一个文件夹并动态加载那里的所有 jar(真的不需要知道它们)为此为了工作,我需要插件中的一个名为 plugin
的文件。我目前有一个可以启动插件的工作类加载器,但我无法读取 plugin
文件。
这是我当前的代码:
加载类
Load(JMenuBar Bar) {
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
ClazzL = new URLClassLoader(new URL[]{new File("/home/grant/plugins/MenuPlugin.jar").toURL()}, currentThreadClassLoader);
Thread.currentThread().setContextClassLoader(ClazzL);
in = new BufferedReader(new InputStreamReader(ClazzL.getClass().getClassLoader().getResourceAsStream("/menuplugin/plugin")));
System.out.println("in: " + in.readLine());
Class c = ClazzL.loadClass("menuplugin.Main");//this works and loads properly
//it is just that it needs to
//load from `plugin` using
//in.readLine();
API obj = (API) c.newInstance();
obj.run(Bar);
}
错误是(第 44 行:in = new Buffered....)
Exception in thread "main" java.lang.NullPointerException
at menuaddon.Load.<init>(Load.java:42)
at menuaddon.Menuaddon.main(Menuaddon.java:39)
Java Result: 1
非常感谢
完成的工作代码是:
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
ClazzL = new URLClassLoader(new URL[]{new File("/home/grant/plugins/MenuPlugin.jar").toURL()}, currentThreadClassLoader);
Thread.currentThread().setContextClassLoader(ClazzL);
in = new BufferedReader(new InputStreamReader(ClazzL.getResourceAsStream("plugin")));
classpath = in.readLine();
Class c = ClazzL.loadClass(classpath);
API obj = (API) c.newInstance();
obj.run(Bar);
最佳答案
如果 ClazzL
实际上是一个变量,并且引用了类加载器,那么尝试一下
ClazzL.getResourceAsStream("/menuplugin/plugin")
相反。如果你执行 ClazzL.getClass().getClassLoader()
,你试图从你的 ClazzL
类的类加载器加载资源,而不是你创建的类加载器。
关于Java 从动态外部 jar 中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416548/