Java ClassLoader:加载相同的类两次 [英] Java ClassLoader: load same class twice

查看:1731
本文介绍了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 将返回现有实例的引用。

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.

回应您的评论:做类似

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

这个类加载器将使用默认委托父类ClassLoader,你必须注意,由它标识的完全限定类名)尚未加载,并且无法由该父类加载器加载。因此,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:加载相同的类两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆