Victor
Victor

Reputation: 17097

Java same class in same package in different projects on Eclipse

If I have 2 java projects in my RAD. Project #1 has a class like this:

/src/com/orgname/model/Model1.java

In Project #2, I also have:

/src/com/orgname/model/Model1.java

Both these classes compile fine. Now in Project #2, I add Project #1 as a build path dependency. Now in my project #2, I write a test class where I do : import com.orgname.model.Model1

Which Model1 will be imported?

Upvotes: 3

Views: 2498

Answers (1)

brettjonesdev
brettjonesdev

Reputation: 2281

Having duplicate copies of classes is a terrible idea! It may compile just fine, and it may even run fine 9 times out of 10, but there is no (simple) way to ensure that one gets loaded over the other at runtime!

In fact, a very common occurrence when duplicates like this exist (whether it be .class files or .jars) is that in some instances version 1 gets loaded, and other times version 2. When this happens and the wrong class is returned, you will get a ClassNotFound or similar Exception. This can be very frustrating to debug, since your code may not fail reliably.

When this happens with artifacts it is referred to as JAR Hell, but the principle is the same: any time you have two copies of a class with the same package and name, you are asking for trouble.

Instead, change the name of Model1 in one of your projects or use different packaging to differentiate the two.

Upvotes: 2

Related Questions