简体   繁体   中英

Groovy GroovyClassLoader JVM Caching and Updating Loaded Classes

I'm testing the dynamic loading of JARS with a GroovyClassLoader . We will be updating the JARs frequently, so we need to re-load the JAR (more specifically, the class) when changes are made without restarting the JVM. Is this possible?

I do classLoader.addUrl(path) once, and the JAR is loaded into memory. I can then generate instances in subsequent scripts without needing to load the class again (that seems like caching which is fine).

The problem is that I tried doing classLoader.clearCache() , and it doesn't seem to have had any effect. .classCache and .sourceCache are empty. But, I can still generate instances. I tried getting the parent classloader , but it doesn't show any trace of the loaded package/class . I'm not sure where it is living.

I also read this article, and no I do not have the class compiled in the JVM.

Classes Loaded by GroovyClassLoader not listed

I don't think my code is relevant, but here it is anyway.

GroovyClassLoader classLoader = new GroovyClassLoader()
def jarFile = new File("C:/sandbox-test-0.1.0-SNAPSHOT.jar")
classLoader.addURL(jarFile.toURI().toURL())
def mySand = Class.forName("com.test.Sandbox").newInstance()
println mySand.dump()

Sascha showed me a brilliantly simple workaround.

To "Update" a classloader, one can simply nullify the existing one and remake:

classloader = null
classloader = new GroovyClassLoader()
classLoader.addURL(jarFile.toURI().toURL())

The classloader is only needed when classes are being requested.

This is simple in my use case. Perhaps others will have more complicated scenarios that might make this not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM