简体   繁体   中英

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.

I have a third module C which I want to use the classes from A and 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?

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. 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. The class which is really used depends on which JAR is first on the classpath which is by coincidence so not predictable.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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