Class getClassLoader() method in Java with Examples


The getClassLoader() method is a method of the java.lang.Class class in Java. It returns the class loader for the class. The class loader is responsible for loading the class into the JVM.

Syntax:

public ClassLoader getClassLoader()

Example 1:

public class Example {
    public static void main(String[] args) {
        ClassLoader classLoader = Example.class.getClassLoader();
        System.out.println(classLoader);
    }
}

Output:

sun.misc.Launcher$AppClassLoader@18b4aac2

In this example, we are using the getClassLoader() method to get the class loader for the Example class. We then print out the class loader using the System.out.println() method.

Example 2:

public class Example {
    public static void main(String[] args) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        System.out.println(classLoader);
    }
}

Output:

sun.misc.Launcher$AppClassLoader@18b4aac2

In this example, we are using the getContextClassLoader() method of the Thread class to get the class loader for the current thread. We then print out the class loader using the System.out.println() method.

Example 3:

public class Example {
    public static void main(String[] args) {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        System.out.println(classLoader);
    }
}

Output:

sun.misc.Launcher$AppClassLoader@18b4aac2

In this example, we are using the getSystemClassLoader() method of the ClassLoader class to get the system class loader. We then print out the class loader using the System.out.println() method.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.