Groovy GroovyClassLoader JVM Caching and Updating Loaded Classes

南笙酒味 提交于 2019-12-13 04:56:38

问题


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()

回答1:


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.



来源:https://stackoverflow.com/questions/35192157/groovy-groovyclassloader-jvm-caching-and-updating-loaded-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!