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:两次加载相同的类
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01