• Post Reply Bookmark Topic Watch Topic
  • New Topic

Duplicate Classes  RSS feed

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess this question is related to the classloader.
If two classes have the same name at runtime which gets loaded?
For example, if I were to create a class called Button and duplicate the package structure of java.awt.Button and put in on the classpath, which class would get loaded? The Button class that I created or the one from rt.jar?
I think I would get a error if I tried to do this a compile time, but if the two classes were created seperately and then placed on the same classpath, would it generate an error?
I hope this is clear what I'm asking.
Regards,
Drew
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two issues here: one is how the compiler resolves names, and the other is how classes are loaded.
First, class loading: generally, with the standard class loader the first class that is found is the one that is loaded. If several instances of class foo.bar.MyClass appear on the classpath, then the one that appears earliest will be loaded first.
Note, however, that the java.* classes aren't loaded by the normal application class loader; they're loaded by the boot class loader which has a different class path, set by using the -Xbootclasspath option. If you defined your own java.awt.Button, it would not be used unless you modified the boot class path to point to it. If you did this, however, then yes, you can replace system classes.
The other issue is compilation. Javac doesn't care about boot class loaders or such. It simply compiles what you give it. You do have to be careful in that if you import like-named classes from two different packages and then use one, the compiler will complain that it doesn't know which class to use. This is generally not too hard to sort out by modifying your import statements and/or using fully qualified class names.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're really stuck with this situation, you can import neither class and put the fully qualified name every time you need it:

Ugly, no? My project uses JAXB which generates some classes with the same name every time, so we wind up with a lot of this. Ick.
[ December 18, 2003: Message edited by: Stan James ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!