mercredi 20 septembre 2017

Why A.class.getClassLoader() does not return the loader used by loader.loadClass("A")

In this test case we are loading a class A through a specific class loader instance, i.e. GwClassLoader. However, the A.class.getClassLoader() does not retrieve that class loader? This is the test case:

class A{
  static {
    ClassLoader loader = A.class.getClassLoader();
    System.out.println("A.<cinit>: " + loader);
  }
}

class ClassLoaderGw extends ClassLoader { }

public class App {
  public static void main(String [] args)  throws ClassNotFoundException,  InstantiationException,  IllegalAccessException {
    ClassLoaderGw loader = new ClassLoaderGw();
    System.out.println("Main: " + loader);
    Class<?> klass = loader.loadClass("A");
    Object obj = klass.newInstance();
  }
}

And, this is the output of running the class App:

Main: ClassLoaderGw@6d06d69c
A.<cinit>: sun.misc.Launcher$AppClassLoader@73d16e93

How can I get the instance of GwClassLoader inside the static constructor of the class A?





Aucun commentaire:

Enregistrer un commentaire