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 and C, 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 of B class, using the forName(String className) API method of Class and then we create a new C 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button