Load class within Jar file and get it's path

◇◆丶佛笑我妖孽 提交于 2020-01-06 01:47:30

问题


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

But when I do this:

File test = new File("path/plugins/MyPlugin.jar/MyPlugin.class");
System.out.println(test.exists());

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

But now, how can I receive the path? Something like URL url = cl.getResource("MyPlugin"); (which gives back a null)


回答1:


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

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

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.




回答2:


If you want to access a file in your jar file you have to put it in the same directory as the class files are.

For example if Main.class is in bin/my/pkg/Main.class you can store your MyPlugin.class in the same directory (bin/my/pkg/MyPlugin.class) and then, if you want to access that file use

URL url = Main.getResource("MyPlugin.class");

Which uses the location of Main.class in your project as root.

Hope it helps!



来源:https://stackoverflow.com/questions/18594923/load-class-within-jar-file-and-get-its-path

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