本文介绍了java类加载器可以多次加载一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java类加载器可以多次加载一个类,即加载一个类的新版本,而不会抛出重复类定义的LinkageError吗?

Can a java classloader load a class more than once, ie load new versions of a class, without throwing a LinkageError of "duplicate class definition"?

在其他如果我们需要动态重新加载一个类,可以使用相同的类加载器完成,还是必须首先销毁类加载器并创建一个新的加载类的新版本?

In other words, if we need to dynamically reload a class, can this be done with the same classloader, or does the classloader have to be destroyed first and a new one be created that will load the new version of the class?

推荐答案

类加载器实际上只能加载一次类!这意味着它只能定义一次。它可以加载很多次,但只是第一次定义它。其余的时间它将加载它已经从第一次定义的现有实例。

A classloader can only actually load a class once! That means that it can only define it once. It can load it many times, but only the first time it will define it. The rest of the times it will load the existing instance it has already defined from the first time.

尝试两次定义类会导致重复类定义的 LinkageError 。如果需要多次加载和重新加载类,那么这必须由不同的类加载器完成,如下所示:

Trying to define a class twice causes a LinkageError of "duplicate class definition". If there is a need for classes to be loaded and reloaded many times then this must be done by different classloaders like this:

当然,这会导致额外负载,但是如果你需要它就可以了。

Of course, this causes an extra load, but if you need it that is OK.

另外,小心不要留下任何类别的引用在销毁类加载器的旧实例时,因为这会导致内存泄漏!

Also, be careful to not leave any references of your classes lying around when destroying the old instance of your classloader, as this will cause a memory leak!

这篇关于java类加载器可以多次加载一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:57