在Jar文件中加载类并获取它的路径 [英] Load class within Jar file and get it's path
问题描述
我知道这里已经有很多类似的问题,但我无法让他们更聪明。我想在jar文件中加载一个类,此时这没有问题,但是当我想将路径传递给我自己的ClassLoader时,它会抛出一个无法找到类的异常。是否可以使用绝对路径在jar中加载类?例如,
Class cls = loader.loadClass(/path/MyPlugin.jar/MyPlugin.class);
I know there are already a lot similar questions here, but I couldn't get any smarter form them. I want to load a class inside a jar file, at this point this is no problem, but when I want to pass the path to my own ClassLoader it throws an exception it cannot find the class. Is it possible to load a class inside a jar using an absolute path? For instance,Class cls = loader.loadClass(/path/MyPlugin.jar/MyPlugin.class);
但是当我这样做时:
File test = new File("path/plugins/MyPlugin.jar/MyPlugin.class");
System.out.println(test.exists());
打印出false。我尝试使用 MyPlugin.jar!/MyPlugin.class
或 MyPlugin.jar.jar!MyPlugin.class
我是哪个我有时在网上看到过,即使我真的不知道这意味着什么......
It prints out false. I tried using MyPlugin.jar!/MyPlugin.class
or MyPlugin.jar.jar!MyPlugin.class
which i've seen sometimes on the web, even though i don't really know what it means...
当我这样做时,它找到了班级:
When I do this it finds the class:
URLClassLoader loader = new URLClassLoader(new URL[] { "path/plugins/MyPlugin.jar" });
Class cl = loader.loadClass("MyPlugin");
但是现在,我该如何收到路径?类似 URL url = cl.getResource(MyPlugin);
(返回null)
But now, how can I receive the path? Something like URL url = cl.getResource("MyPlugin");
(which gives back a null)
推荐答案
您可以使用 ClassLoader.getResources 。要查找具有特定类的jar,您可以使用以下
You can obtain URLs to classpath resources using ClassLoader.getResources. To find a jar with specific class, you may use the following
URL url = classLoader.getResource("com/example/SomeClass.class");
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile file = connection.getJarFile();
String jarPath = file.getName();
其中 classLoader
是任何能够查找的类加载器要加载的类。如果jar是应用程序类路径的一部分,则可以使用系统类加载器:
where classLoader
is any classloader capable of finding the class you want to load. If the jar is a part of your application's classpath, you may use system classloader:
ClassLoader classLoader = ClassLoader.getSystemClassloader();
否则,您需要事先知道jar文件位置,并创建一个<$ c $的实例c> URLClassLoader ,在构造函数中传递jar:
Otherwise, you need to know the jar file location beforehand, and create an instance of URLClassLoader
, passing the jar in the constructor:
ClassLoader classLoader = new URLClassLoader(new URL[]{new URL("path/to/the/jar/file.jar")});
然后用它来加载你的课程。
and then use it to load your class.
这篇关于在Jar文件中加载类并获取它的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!