4

我在不同的 JAR 中有两个具有相同包的类。直到以前的版本,这两个类都是相同的,所以我在加载它们时没有问题。现在,其中一个添加了一个新方法,如果我想访问它,我不仅应该使用该包导入类,我还需要确保具有正确类的 jar 在类路径中首先出现。

IEjavac -classpath "%classpath%;a.jar;b.jar" MyClasses..

我的新方法在哪里a.jar上课。

现在,当我的应用程序投入生产时,我如何确保这一点,它被部署为 EAR 文件,所有库都在 WEB-INF/lib 下?

我怎么知道哪个罐子比另一个罐子更受欢迎?是不是像 a.jar 这样的字母顺序优先于 b.jar?

我已经阅读了这个safe-class-imports-from-jar-files线程并了解了如何编写自定义类加载器,但是有没有更好更简单的解决方案呢?因为我只是要在当前项目的整个 JAR 中访问此方法,而编写类加载器似乎有点矫枉过正。

并且请不要问我“为什么在不同的 JAR 中具有相同的包的同一个类?” 这完全超出了我的控制,需要一些时间才能纠正。

环境细节:IBM WAS 6.1 on their 1.5 Java。

如果我没有多大意义,请再问我一些问题。提前致谢!

4

6 回答 6

3

据我所知,从 WEB-INF/lib 加载 jar 的顺序是任意的——我问了一个关于 JBOSS 的类似问题并得到了答复(来自 RedHat),它取决于java.io.File.listFiles()返回它们的顺序(即不是保证订单)。

自定义类加载器将是一个选项,但您是否考虑过重新打包 jar - 删除重复的类?

于 2011-04-28T11:31:18.717 回答
3

您可以尝试更改服务器的启动脚本,并使用java -Xbootclasspath... 在 bootclasspath 中指定具有正确类的 jar。否则无法保证 2 个 jar 中的哪一个将首先加载。

于 2011-04-28T11:37:05.307 回答
2

Websphere allows you to specify the order in which classloaders of a particular application are inquired when searching for a class (the classloaders are hierarchically structured, from the topmost that loads JRE classes, down to classloader loading classes in your WAR).

During deployment of an app, you can specify if the order of inquiring the classloaders when searching for a class. There are two modes - Parent first (i.e. query the topmost classloader first) and parent last (query the app classloader first). This can be specified on both EAR and WAR level.

Packaging the duplicated jars to different locations in the app (e.g. one to EAR's classpath, the other to WAR's WEB-INF/lib) and setting the classloader orderING apropriately may solve your problem. However, if both your JARs have to be on the same level (e.g. WEB-INF/lib), then there's no way to specify which one will be used when loading the duplicated class.

于 2011-04-28T11:41:42.217 回答
1

假设您对部署有一定的控制权,请自己修复类加载。通过将有问题的 jar 以反向加载顺序解压缩到同一目录中,然后重新压缩到新 jar 中,自己组合有问题的 jar。然后使用新的组合 jar 部署应用程序。没有重复的类,问题解决了。

或者,在部署之前从 jars 中删除 dupe 类。

于 2011-04-28T11:58:25.267 回答
1

一个应用程序中 JAR 的顺序可能是按字母顺序排列的,但应用程序的顺序可能不是。此外,这取决于服务器如何处理类加载,即它是替换现有类还是跳过新类。

尽管您已经说过,但我仍然想给出这样的建议:在一个应用程序中部署的多个 JAR 中具有相同的类(例如,这可能发生在版本化的 jar 中)总是一个坏主意。你最好花时间来解决这个问题,而不是试图搞乱类加载。

于 2011-04-28T11:34:45.340 回答
1

这可能会很模糊,但我确实记得很久以前通过为给定的应用程序处理 WAS 管理控制台并使用他们的 Web UI 重新排列相关的 JAR 文件来解决这个问题。不确定这在您的情况下是否是可接受的步骤,但值得一试,以防其他一切都失败。

于 2011-04-28T11:40:09.210 回答