Java Class getClassLoader() Method
The getClassLoader() method of java Class class returns the class loader for the class which called this method. If this class is loaded by the bootstrap class loader, then it will return null.
Syntax
public ClassLoader getClassLoader()
Parameter
No parameter is passed.
Returns
Return the class loader.
Throws
SecurityException
Example 1
//import statements
import java.lang.*;
public class ClassgetClassLoaderExample1 {
public static void main(String[] args) {
try {
Class clsobj = Class.forName("Class.ClassgetClassLoaderExample1");
ClassLoader ClsLoader = clsobj.getClassLoader();
if (ClsLoader == null) {
System.out.println("System class was used.");
} else {
// returns the class loader
Class loaderCls = ClsLoader.getClass();
System.out.println("Associated with ClassLoader = " +loaderCls.getName());
} catch (ClassNotFoundException e) {
System.out.println(e.toString()); //coverting exception object to string and printing it
Test it Now
Output:
Associated with ClassLoader = sun.misc.Launcher$AppClassLoader
Example 2
//import statements...
public class ClassgetClassLoaderExample2 {
public static void main(String[] args) throws Exception {
Class clsobj = Class.forName("java.lang.String");
ClassLoader ClassLoader = clsobj.getClassLoader();
if (ClassLoader == null) {
System.out.println("System class is used...");
} else {
Class loaderClass = ClassLoader.getClass();
System.out.println(loaderClass.getName());
Test it Now
Output: