简体   繁体   English

从2个不同的模块导入具有相同名称和包的2个不同的类

[英]Importing 2 different classes with same name and packages from 2 different modules

In my project I have 2 sub modules, let's call them module A and module B. They both have the structure of com.example.MyClass.java as their class. 在我的项目中,我有2个子模块,我们将它们分别称为模块A和模块B。它们都具有com.example.MyClass.java的结构作为其类。

I have a third module C which I want to use the classes from A and B. 我有第三个模块C,我想使用A和B中的类。

But when I try to do so I can only implement the class from the first module added under . 但是,当我尝试这样做时,我只能从下添加的第一个模块中实现类。

Is there a way like A.com.example.MyClass and B.com.example.MyClass so I could use them at the same class? 有没有类似A.com.example.MyClass和B.com.example.MyClass的方法,所以我可以在同一个类中使用它们?

First this sounds like a design flaw to me cause having the same package names sounds that you haven't separated on the package level which you already did on the maven module level so not representing that same segregation level on the package level as well. 首先,这听起来像是我的设计缺陷,这是因为在包级别上具有与在maven模块级别上尚未分离的相同的包名称声音,因此也不能在包级别上代表相同的隔离级别。 This will usually happen if you have different groups of classes...apart from that If you have the exact same package and class name that is simply not possible cause a classname must be unique within a package which is violated here. 如果您有不同的类组,通常会发生这种情况...除此之外,如果您拥有完全相同的包和类名,这是完全不可能的,因为在此违反的包中,类名必须是唯一的。 The result will be having two different JAR's on classpath which offer the same class. 结果将在提供相同类的classpath上具有两个不同的JAR。 The class which is really used depends on which JAR is first on the classpath which is by coincidence so not predictable. 实际使用的类取决于哪个JAR首先位于类路径上,这是巧合的,因此无法预测。

OSGi will not help here cause you have the same problem here cause you would like to access the same class from different bundles which is not possible to solve. OSGi在这里无济于事,因为您有同样的问题,在这里由于您想从不同的包访问相同的类而无法解决。 Furthermore in JDK 9 this will not work either cause those classes have to be made public (same as in OSGi) which will fail as well. 此外,在JDK 9中这也不起作用,因为必须公开这些类(与OSGi中相同),这也会失败。

If you want to both classes have the same name you have to change a package name for one of the classes. 如果要使两个类具有相同的名称,则必须更改其中一个类的程序包名称。 Otherwise, there is no way to import both classes. 否则,将无法导入两个类。

Another solution is to change class name for one of those classes. 另一种解决方案是更改其中一个类的类名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM