androidguy
androidguy

Reputation: 121

Does every "new" result in at least one Classloader.loadClass invocation

I noticed that we can set a Thread's context classloader at will. Does it mean that every new results in the context classloader's loadClass getting called?

Upvotes: 1

Views: 141

Answers (2)

Mohammadreza  Alagheband
Mohammadreza Alagheband

Reputation: 2230

Class loading by ClassLoaders can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs but you should be aware that the behavior might not exactly the same as new in some scenarios and might be the same in others. If Class is loaded before its actually being used it can sit inside before being initialized. this might vary from JVM to JVM, but its guaranteed by JLS that a class will be loaded when there is a need of static initialization.

as also explained in What does "new" do in Java w.r.t. class loader?:

Class loading is performed only once for a given namespace, unless the Class in question has been previously unloaded. Therefore, the equivalent expression A.class.getClassLoader().loadClass("B's canonical name") will be executed only once in most scenarios. In other words, if you have two expressions - new A(), the loadClass will be performed only once.

Upvotes: 0

Mike Nakis
Mike Nakis

Reputation: 61993

No, loadClass() will only be invoked once, the first time the class is accessed. (This will not necessarily happen on new(), it may happen if you try to access a static member of the class.)

In every subsequent access of the class, loadClass() will not be invoked.

That's because every time the class is needed, the ClassLoader invokes findClass() internally, which tries to find an already loaded class, so if the class has already been loaded, the ClassLoader refrains from invoking loadClass() again.

Upvotes: 4

Related Questions