Java Class getEnclosingConstructor() Method



Description

The java Class getEnclosingConstructor() method returns a Constructor object representing the immediately enclosing constructor of the underlying class, if this Class object represents a local or anonymous class within a constructor else returns null.

Declaration

Following is the declaration for Java Class getEnclosingConstructor() method

public Constructor<?> getEnclosingConstructor()

Parameters

NA

Return Value

This method returns the immediately enclosing constructor of the underlying class, if that class is a local or anonymous class, else null.

Exception

NA

Getting Enclosing Class of the Underlying Class Example

The following example shows the usage of java.lang.Class.getEnclosingConstructor() method. In this program, we've created a Class ClassDemo. In ClassDemo constructor, a new class is created as ClassA. In main method, we've retrieved class of ClassDemo and then using getEnclosingConstructor() method, enclosing constructor is received and printed.

package com.tutorialspoint;

public class ClassDemo {

   public Object c;

   public ClassDemo( ) {
      class ClassA{ };
      c = new ClassA( );
   }

   public Object ClassAObject( ) {
      class ClassA{ };
      return new ClassA( );
   }

   public static void main(String[] args) {
     
      Class cls;
      cls = (new ClassDemo()).c.getClass();

      System.out.print("getEnclosingConstructor() = ");
      System.out.println(cls.getEnclosingConstructor());
   }
} 

Output

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

getEnclosingConstructor() = public com.tutorialspoint.ClassDemo()

Getting Enclosing Constructor of the ArrayList Class Example

The following example shows the usage of java.lang.Class.getEnclosingConstructor() method. In this program, we've used class of ArrayList. Then using getEnclosingConstructor(), enclosing Constructor is checked and printed.

package com.tutorialspoint;

import java.util.ArrayList;

public class ClassDemo {
   public static void main(String[] args) {
      Class cls = ArrayList.class;
      
      System.out.println(cls.getEnclosingConstructor());
   }
}

Output

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

null

Getting Enclosing Constructor of the Thread Class Example

The following example shows the usage of java.lang.Class.getEnclosingConstructor() method. In this program, we've used class of Thread. Then using getEnclosingConstructor(), enclosing Constructor is checked and printed.

package com.tutorialspoint;

public class ClassDemo {
   public static void main(String[] args) {
      Class cls = Thread.class;
      
      System.out.println(cls.getEnclosingConstructor());
   }
}

Output

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

null
java_lang_class.htm
Advertisements