1

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?

3
  • 1
    Do you mean accidentally? Or is this what you're trying to achieve? Commented Nov 24, 2014 at 6:45
  • yups.. accidentally.. is ther any probability Commented Nov 24, 2014 at 6:46
  • No.. Unless you are doing it wrong it won't happen. Commented Nov 24, 2014 at 6:48

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.