Search code examples
javaclassloaderurlclassloader

ClassLoader: pretend that a class wasn't found so a child loader can handle it instead


I want to make a subclass of URLClassLoader which, when loadClass() is invoked, can examine the loaded class with reflection and conditionally decide to pretend it couldn't find that class, so as to allow for a child class loader to handle the loading instead. Would something like the following work?

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    Class<?> c = super.findClass(name);

    if (letChildHandleLoad(c))
        throw new ClassNotFoundException();

    return c;
}

Solution

  • The default behavior for loadClass is to call getParent().loadClass and then findClass. To get the behavior you're describing, typically you would not modify the parent class loader; instead, typically you would modify the child class loader by overriding the loadClass method to call findClass first. That way, loadClass calls that originate with the child class loader will load the class from its local class path before the parent, but loadClass calls that originate with the parent class loader will work as expected.