6

假设我有两个类(鲍勃和汤姆),鲍勃使用汤姆,但汤姆不需要鲍勃。这两个文件都位于相同的目录结构中。

public class Bob {
  public static void main(String[] args) {
    System.out.println(Tom.MESSAGE);
  }
}

public class Tom {
  public static String MESSAGE = "Hello World";
}

如果我尝试以典型方式编译 Bob,我也可以让它隐式编译Tom.java,因为它被识别为Bob.java. 这很好用。

但是现在假设我想将 Tom 放在一个 JAR 文件中。所以我构建Tom.java并将结果放入一个 JAR 文件:libTom.jar。我现在用指向的类路径进行编译libTom.jar。不幸的是,编译器看到该Tom.java文件并导致它被编译,而不是使用libTom.jar. 有没有办法让编译器跳过在Tom.java类路径中找到类的隐式构造?

我承认这个例子是相当做作的。请放心,围绕这个问题有一个更复杂、更少人为的用例。谢谢。

4

4 回答 4

1

如果类路径中有两个同名且在同一个包中的类,那么当java编译代码时,很难预测哪一个会被拾取。如果Tom该类存在于源本身中,它肯定会被拾取。

避免这种情况的一种方法是将其中一个Toms 放在不同的包中。另一种方法是,如果你可以将你的当前移动Tom到一个单独的项目。我知道其中任何一个对您来说可能都不实用。如果确实有必要,您可以尝试编写自己的 ClassLoader。请参阅此问题以供参考:Jar hell: how to use a classloader to replace one jar library version with another at runtime

于 2012-06-01T20:31:26.437 回答
1

It appears that this just isn't possible, which is what I feared from the beginning.

于 2012-06-02T06:17:43.820 回答
0

是的,你可以通过输入一个类的全名来做到这一点,即 Typing

System.out.println(the.package.of.external.Tom.MESSAGE);
System.out.println(the.current.package.Tom.MESSAGE);

于 2012-06-01T20:29:22.170 回答
0

Can you split the java files into separate source directories? This would make sense as you could build your jar from the contents of one source dir, then just include the other source dir when compiling all the other set of files. This works well in Eclipse. Even better would be to use two projects in Eclipse.

于 2012-06-01T20:43:48.367 回答