Java ClassLoader:两次加载相同的类

2022-01-17 00:00:00 class compiler-construction java

我有一个 ClassLoader 从源文件加载由 JavaCompiler 编译的类.但是当我更改源文件,保存并重新编译时,ClassLoader 仍然会加载该类的第一个版本.

I have a ClassLoader which loads a class compiled by JavaCompiler from a source file. But when I change the source file, save it and recompile it, the ClassLoader still loads the first version of the class.

   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   Class<?> compiledClass = cl.loadClass(stringClass);

我错过了什么?比如 newInstance 什么的?

What am I missing? like a newInstance or something?

推荐答案

类加载器不能替换已经加载的类.loadClass 将返回现有 Class 实例的引用.

A classloader can't replace a class that already has been loaded. loadClass will return the reference of the existing Class instance.

您必须实例化一个新的类加载器并使用它来加载新类.然后,如果你想替换"这个类,你就必须扔掉这个类加载器并创建另一个新的.

You'll have to instantiate a new classloader and use it to load the new class. And then, if you want to "replace" the class, you'll have to throw this classloader away and create another new one.

回应您的评论:做类似的事情

In response to your comment(s): do something like

ClassLoader cl = new UrlClassLoader(new URL[]{pathToClassAsUrl});
Class<?> compiledClass = cl.loadClass(stringClass);

该类加载器将使用默认委托父类加载器",您必须注意,该类(由其完全限定的类名标识)尚未加载并且无法由该父类加载器加载.所以pathToClassAsUrl"不应该在类路径上!

This classloader will use the "default delegation parent ClassLoader" and you have to take care, the class (identified by it fully qualified classname) has not been loaded and can't be loaded by that parent classloader. So the "pathToClassAsUrl" shouldn't be on the classpath!

相关文章