1

Class B shall be loaded with the same ClassLoader that loaded class A (proof-link).

class A {

   B fld = new B();

   void f() {
      B loc_var = new B();
   {

}

But what happens, if class B has already been loaded with a different class-loader before?

Any class is loaded only once. But classes loaded by different clas-loaders are different classes.

So class B would be loaded one more time by classloader of class A and two different(!) classes would coexist (within same JVM instance)?

Code Complete
  • 3,146
  • 1
  • 15
  • 38
  • So your question is how does the class loader of A know that the class is loaded when it was not the one that loaded it? – Michael Jan 04 '19 at 15:22
  • Question is: Is that right that class B would get loaded for the second time (with another classLoader - namely with classLoader which loaded class A) – Code Complete Jan 04 '19 at 15:44
  • No, it only gets loaded once. – Michael Jan 04 '19 at 16:09
  • If you’re saying that class B is in the same .jar file as class A, then yes, class B will also be loaded more than once. – VGR Jan 04 '19 at 17:47

1 Answers1

1

It depends on what kind of these two ClassLoaders. JVM has three kinds: Bootstrap ClassLoader, Extension ClassLoader, and Application ClassLoader. When finding a Class, first, JVM will look in Bootstrap ClassLoader, then Extension and Application. So if two ClassLoaders are a different kind, the Class will load only once. If two ClassLoaders are both Application ClassLoader, it will load twice. Which Class is used, it depends on invoker's ClassLoader.

Juey
  • 123
  • 1
  • 6