Java的类加载器与jars-within-jars [英] Java's classloader versus jars-within-jars

查看:102
本文介绍了Java的类加载器与jars-within-jars的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个可执行的JAR文件,有时包含其他JAR文件。 (整个事情依赖于其他四个下载的JAR,位于太空中巨型部署乌龟的背面。)在运行时,我们动态加载嵌套的JAR文件,执行以下操作:

We have an executable JAR file that sometimes contains other JAR files. (The whole thing rests on four other downloaded JARs, riding on the back of a giant deployed turtle in space.) At runtime, we dynamically load that nested JAR file doing the following:

// wearyingly verbose error handling elided

URL nestedURL = the_main_system_classloader.getResource("path/to/nested.jar");
File temp = File.createTempFile (....);
// copy out nestedURL contents into temp, byte for byte

URL tempURL = temp.toURI().toURL();
URLClassLoader loader = URLClassLoader.newInstance(new URL[]{ tempURL });
Class<?> clazz = loader.loadClass("com.example.foo.bar.baz.Thing");
Thing thing = (Thing) clazz.newInstance();
// do stuff with thing

这种技术之前已经提到过;链接包括这一个这一个。我们目前使用的代码有效...

This kind of technique has been brought up here before; links include this one and this one. The code we currently have in place works...

...主要是。我真的想找到一些方法来避免临时文件的创建和复制(以及最终的清理,因为我们都知道, deleteOnExit是邪恶的)。毕竟,在开始时获得的URL指向JAR:

...mostly. I'd really like to find some way of avoiding the temporary file creation and copying (and eventual cleanup, because as we all know, deleteOnExit is evil). The URL obtained right at the start points to a JAR, after all:

URL nestedURL = the_main_system_classloader.getResource("path/to/nested.jar");
// nestedURL.toString() at this point is
// "jar:file:/C:/full/path/to/the/executable.jar!/path/to/nested.jar"
URLClassLoader loader = URLClassLoader.newInstance(new URL[]{ nestedURL });
Class<?> clazz = loader.loadClass("com.example.foo.bar.baz.Thing");

但是loadClass会抛出一个ClassNotFound。

But loadClass throws a ClassNotFound.

URLClassLoader可以简单地处理这个JAR-in-a-JAR案例吗?或者我是否需要对所涉及的一个或多个路径(nestedURL或传递给loadClass的字符串)执行某些操作?

Can the URLClassLoader simply not handle this JAR-within-a-JAR case? Or do I need to do something to one or more of the paths involved (either the nestedURL or the string passed to loadClass) to make this work?

推荐答案

AFAIK香草URLClassloader无法处理它。

AFAIK the vanilla URLClassloader cannot handle it.

到目前为止这是你的答案。

So far this is your answer.

除了你的解决方案之外,我还有两个其他的可能性:

Apart from your solution there are two other possibilities that I am aware of:


  1. 创建一个胖罐(p.ex.使用Maven Shade )

  2. 创建一个自定义类加载器,但这是一项艰苦的工作。

这篇关于Java的类加载器与jars-within-jars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆