Java ClassLoader:两次加载相同的类

2023-10-15Java开发问题
202

本文介绍了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:两次加载相同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13