Java ClassLoader: load same class twice(Java ClassLoader:两次加载相同的类)
问题描述
我有一个 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!
这篇关于Java ClassLoader:两次加载相同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java ClassLoader:两次加载相同的类
基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01