开发者

What happens if we load already loaded class again?

开发者 https://www.devze.com 2022-12-24 11:53 出处:网络
I mean we have a class which is already loaded in JVM. and in some other method we are unknowingly trying to load that same class, So in this situation what happens? ie will there be any error or exce

I mean we have a class which is already loaded in JVM. and in some other method we are unknowingly trying to load that same class, So in this situation what happens? ie will there be any error or exception saying its alrea开发者_高级运维dy loaded. If not, then is it possible that we can have modified class with some extra features and load it whenever it is required that is Hot Deployment.


Nothing happens. The VM first checks whether the class is loaded and loads it only if not. Otherwise it returns the already loaded class.

From ClassLoader.loadClass(..):

// First, check if the class has already been loaded
Class c = findLoadedClass(name);
if (c == null) {
    ...
}

(You can check this article on extensive details on class loading. Although it is not directly related (as a whole) to your question, it is a good source of answers for questions like yours)


If your looking to reuse a class while its loaded you should check out the Singleton Class Pattern. If you load the same class again well then you are going to have multiple instances of the class, no error will occur.


There can be only one class per class loader, so this is theoretically not possible. You can actually test this by calling putting S.o.p statements in the static initializer blocks. These blocks are run only once when the class is getting loaded.

Edit

One class of a given fully qualified name, corrected as per the comment

0

精彩评论

暂无评论...
验证码 换一张
取 消