I have a same class belonging to 2 different packages.
package x1.y1.Class
packgage x2.y2.Class
Is it possible that if I am invoking a x1.y1.Class via classloader, x2.y2.Class loads instead?
-
1Do you mean accidentally? Or is this what you're trying to achieve?Jon Skeet– Jon Skeet2014年11月24日 06:45:39 +00:00Commented Nov 24, 2014 at 6:45
-
yups.. accidentally.. is ther any probabilityvegeta– vegeta2014年11月24日 06:46:16 +00:00Commented Nov 24, 2014 at 6:46
-
No.. Unless you are doing it wrong it won't happen.TheLostMind– TheLostMind2014年11月24日 06:48:25 +00:00Commented Nov 24, 2014 at 6:48
2 Answers 2
Simply said, no (unless you unintentionally load the wrong one).
Classes are loaded by their fully-qualified class-name, which includes the package (e.g. x1.y1.Class)
Comments
No, it can't happen, for two reasons:
- The classloader finds the class by package, by looking in the right place
- Even if you accidentally put a class in the wrong place, the class file itself includes the package name, and this is checked during class loading.
I've just tried doing this deliberately, replacing p1/Foo.class with the file for class p2.Foo, and received the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: p1/Foo (wrong name: p2/Foo)
If you wanted to do this, you'd need a classloader which deliberately looked in the wrong location, and then modified the bytecode it loaded.