Groovy multiple classLoaders

21 / Feb / 2014 by Amit Jain 0 comments

I never had to worry about whether the classes loaded in our application are in the same class loader or different, until I was stuck with the weird class not found exception. We were using a third party tool (Snowbound’s DocViewer) which provided around 10 jar files, which worked well for except one functionality which was provided by 3 separate jar files that always came up with “class not found exception”. All 10 jar files were loaded the same way i.e from the artifactory or even tried adding them to the grails-app/lib folder but to no avail.

After digging more into it, we found that class in question is loaded in some other classLoader, not sure the reason yet. Also found that child classLoader can find the class loaded in parent classLoader but not the vice versa.
So we decided to load jars files in question, to the rootLoader but found at many places rootLoader was null so it didn’t help either. Then we decided to load the jars files into top most parent class loader, see the sample below :
[groovy]
def classLoader = BootStrap.class.classLoader

while(classLoader.parent){ //identify topmost class loader.
classLoader = classLoader.parent
}

// find path to the jars files, which are located in web-app/jars
String jarsPath = "file:///" + grailsApplication.getParentContext().getServletContext().getRealPath("/jars")

classLoader.addURL(new URL(jarsPath + ‘/1st.jar’));
classLoader.addURL(new URL(jarsPath + ‘/2nd.jar’));
[/groovy]

Voilla it just worked.

Hope this helped.

Cheers!
~~Amit Jain~~
amit@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *