Java.lang.Class.getEnclosingClass() Method

Advertisements


Description

The java.lang.Class.getEnclosingClass() method returns the immediately enclosing class of the underlying class. If this class is a top level class this method returns null.

Declaration

Following is the declaration for java.lang.Class.getEnclosingClass() method

public Class<?> getEnclosingClass()

Parameters

  • NA

Return Value

This method returns the immediately enclosing class of the underlying class.

Exception

  • NA

Example

The following example shows the usage of java.lang.Class.getEnclosingClass() method.

package com.tutorialspoint;

import java.lang.*;

public class ClassDemo {
   // constructor
   public ClassDemo() {
        
      // class Outer as inner class for class ClassDemo
      class Outer {
            
         public void show() {
            // inner class of Class Outer
            class Inner {

               public void show() {
                  System.out.print(getClass().getName() + " inner in...");
                  System.out.println(getClass().getEnclosingClass());    
               }
            }
            System.out.print(getClass().getName() + " inner in...");
            System.out.println(getClass().getEnclosingClass());

            // inner class show() function
            Inner i = new Inner();
            i.show();
         }
      }

      // outer class show() function
      Outer o = new Outer();
      o.show();
   }

   public static void main(String[] args) {
     ClassDemo cls = new ClassDemo();
   }
}

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

ClassDemo$1Outer inner in...class ClassDemo
ClassDemo$1Outer$1Inner inner in...class ClassDemo$1Outer



Advertisements
Advertisements