class
How the class loader works
In this example we shall show you how the class loader works. To see how the class loader works we have performed the following steps:
- We have created three classes,
A
,B
andC
, that each one uses a static block to print a message. The code in a static block is executed when the class is loaded by the class loader. - We create a new instance of
A
class, then we get an object ofB
class, using theforName(String className)
API method of Class and then we create a newC
object and see the printed messages from the static blocks,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; class A { static { System.out.println("Loading A"); } } class B { static { System.out.println("Loading B"); } } class C { static { System.out.println("Loading C"); } } public class ClassLoader { public static void main(String[] args) { System.out.println("inside main"); new A(); System.out.println("inside main : After creating A"); try { Class.forName("B"); } catch (ClassNotFoundException e) { System.out.println("inside main : Couldn't find B"); } System.out.println("inside main : After Class.forName("B")"); new C(); System.out.println("inside main : After creating C"); } }
Output:
inside main
Loading A
inside main : After creating A
inside main : Couldn't find B
inside main : After Class.forName("B")
Loading C
inside main : After creating C
This was an example of how the class loader works in Java.