Search code examples
javaclassloader

Is Java Classloader Delegation model mandatory?


If i have a custom classloader which, instead of delegating to its parent first, tries a search and load of the class itself will it be a violation of some stated/unstated rule?


Solution

  • The Tomcat webapp classloader follows this model, so I imagine it works to at least some extent :) From the Tomcat classloader documentation:

    As mentioned above, the web application class loader diverges from the default Java 2 delegation model (in accordance with the recommendations in the Servlet Specification, version 2.4, section 9.7.2 Web Application Classloader). When a request to load a class from the web application's WebappX class loader is processed, this class loader will look in the local repositories first, instead of delegating before looking. There are exceptions. Classes which are part of the JRE base classes cannot be overriden. For some classes (such as the XML parser components in J2SE 1.4+), the J2SE 1.4 endorsed feature can be used. Last, any JAR file that contains Servlet API classes will be explicitly ignored by the classloader — Do not include such JARs in your web application. All other class loaders in Tomcat 6 follow the usual delegation pattern.

    It sounds to me like you should be very cautious before you do this, but in certain cases it could be useful, if used carefully. You should document it thoroughly (particularly if this will be seen by third party developers) and make sure you include enough logging/diagnostics to help troubleshoot thorny problems.