Java Classloading

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow