Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the Java Class loader?

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.

like image 732
Naveen kapoor Avatar asked Jun 29 '11 10:06

Naveen kapoor


3 Answers

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:

  • JavaRanch: When is a class loaded?
  • The Basics of Java Class Loaders

why do we need the notion of a class loader

Class loaders allow us to load classes from various sources.

  • a jar file on disk
  • a runtime generated byte-array
  • from the Internet (which is a typical use case for applets)

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.

like image 190
aioobe Avatar answered Nov 07 '22 15:11

aioobe


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  
  }  
}
like image 2
Saurabh Gupta Avatar answered Nov 07 '22 13:11

Saurabh Gupta


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).

like image 1
setec Avatar answered Nov 07 '22 15:11

setec