Java ClassLoader getParent() Method



Description

The Java ClassLoader getParent() method returns the parent class loader for delegation. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class loader's parent is the bootstrap class loader.

Declaration

Following is the declaration for java.lang.ClassLoader.getParent() method

public final ClassLoader getParent()

Parameters

NA

Return Value

This method returns the parent ClassLoader

Exception

SecurityException − If a security manager exists and its checkPermission method doesn't allow access to this class loader's parent class loader.

Getting Parent ClassLoader Example

The following example shows the usage of java.lang.ClassLoader.getParent() method. In this program, we've retrieved class of a ClassLoaderDemo. Then using getClassLoader(), we get the required ClassLoader and printed class loader class using getClass() and printed the parent class loader using getParent() method.

package com.tutorialspoint;

public class ClassLoaderDemo {

  public static void main(String[] args) throws Exception {
     
      Class cls = Class.forName("com.tutorialspoint.ClassLoaderDemo");

      // returns the ClassLoader object associated with this Class
      ClassLoader cLoader = cls.getClassLoader();
    
      System.out.println(cLoader.getClass());
    
      // returns the parent ClassLoader
      System.out.println(cLoader.getParent());
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

class jdk.internal.loader.ClassLoaders$AppClassLoader
jdk.internal.loader.ClassLoaders$PlatformClassLoader@4517d9a3

Getting Parent ClassLoader of Child Class Example

The following example shows the usage of java.lang.ClassLoader.getParent() method. In this program, we've retrieved class of a TestInnerClass. Then using getClassLoader(), we get the required ClassLoader and printed class loader class using getClass() and printed the parent class loader using getParent() method.

package com.tutorialspoint;

public class ClassLoaderDemo {

   public static void main(String[] args) throws Exception {

      TestInnerClass innerClass  = new ClassLoaderDemo(). new TestInnerClass();
      Class cls = innerClass.getClass();

      // returns the ClassLoader object associated with this Class
      ClassLoader cLoader = cls.getClassLoader();

      System.out.println(cLoader.getClass());

      // returns the parent ClassLoader
      System.out.println(cLoader.getParent());
   }

   class TestInnerClass {
      // sample data
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

class jdk.internal.loader.ClassLoaders$AppClassLoader
jdk.internal.loader.ClassLoaders$PlatformClassLoader@372f7a8d
java_lang_classloader.htm
Advertisements