My question is, when does JVM load all the classes in the project? Also, why do we need the notion of a class loader.
I'd be happy if you could give me a example of a situation where you use class loader and why you use class loader in that situation.
when does JVM load all the classes in the project.
The JVM loads the classes more or less "on demand". I.e. all classes in the runtime will typically not be loaded upon launch.
Refer to these URLs for details on this topic:
why do we need the notion of a class loader
Class loaders allow us to load classes from various sources.
This makes the launch of an application more flexible and modular.
give me a example with situation where you use class loader and why you use class loader there.
Without a class-loader you won't get far, so I'll interpret your question as "when do you need a custom class loader".
Personally I did some experiments using a byte-code manipulation library (ASM) where I replaced field accesses with get- and set-method calls. I used a custom class loader to rewrite the classes as they were loaded. I don't know if it's a typical use case, but the point is that I couldn't have done this without one!
You could also imagine a plugin-system which loads peripheral classes from some plugin directory.
A class is loaded whenever it is executed directly orif it is referenced in another class which is to be executed... for example
class A
{}
class B extends A
{
public static void main(String arr[])
{}
}
here whenever u get execute class B,the class A is loaded automatically
now consider this
class A
{}
class B
{
public static void main(String arr[])
{
A ob=new A();//here class A is need to be loaded by JRE
}
}
JVM load classes on demand. When you need class to be explicitly loaded, you need to make reference to that class from the main class, for example
static {
MyClass.class.getName();
}
Custom classloader is rarely needed, most commons cases are: AOP (for example runtime on-load instrumentation of classes with Javassist), remote class loading (loading a class from remote location), encrypted class loading (deciphering class code and loading).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With