简体   繁体   English

Groovy GroovyClassLoader JVM缓存和更新加载的类

[英]Groovy GroovyClassLoader JVM Caching and Updating Loaded Classes

I'm testing the dynamic loading of JARS with a GroovyClassLoader . 我正在使用GroovyClassLoader测试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. 我们将经常更新JAR,因此在进行更改时需要重新加载JAR(更具体地说是类),而无需重新启动JVM。 Is this possible? 这可能吗?

I do classLoader.addUrl(path) once, and the JAR is loaded into memory. 我只执行一次classLoader.addUrl(path) ,然后将JAR加载到内存中。 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. 问题是我尝试做classLoader.clearCache() ,但似乎没有任何效果。 .classCache and .sourceCache are empty. .classCache.sourceCache为空。 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. 我也阅读了这篇文章,没有,我没有在JVM中编译该类。

Classes Loaded by GroovyClassLoader not listed GroovyClassLoader加载的类未列出

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. Sascha向我展示了一个非常简单的解决方法。

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. 也许其他人会遇到更复杂的情况,这可能使它不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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