Groovy GroovyClassLoader JVM缓存和更新加载的类 [英] Groovy GroovyClassLoader JVM Caching and Updating Loaded Classes
问题描述
我使用 GroovyClassLoader
来测试JARS的动态加载。我们会经常更新JAR,所以我们需要在不重新启动JVM的情况下重新加载JAR(更具体地说,是类)。这是可能的吗?
我做了 classLoader.addUrl(path)
一次,然后将JAR加载到内存中。然后,我可以在后续脚本中生成实例,而无需再次加载类(这看起来像是缓存,这很好)。
问题是我试着做 classLoader.clearCache()
,它似乎没有任何效果。 .classCache
和 .sourceCache
为空。但是,我仍然可以生成实例。我尝试获取父类加载器,但它没有显示任何加载的包/类的踪迹。我不确定它在哪里生活。
我也读过这篇文章,并且没有我没有在JVM中编译过的类。
我不认为我的代码是相关的,但在这里它是无论如何。
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()
我是一个非常简单的解决方法。
要更新类加载器,可以简单地取消现有的类并重新制作:
classloader = null
pre>
classloader = new GroovyClassLoader()
classLoader.addURL(jarFile.toURI()。toURL())
类加载器仅在需要类时才需要。
这在我的用例中很简单。也许其他人会有更复杂的情况下,可能会使这不起作用。
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.
这篇关于Groovy GroovyClassLoader JVM缓存和更新加载的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!