Java Class getEnclosingMethod() Method



Description

The Java Class getEnclosingMethod() method returns a Method object representing the immediately enclosing method of the underlying class, if this Class object represents a local or anonymous class within a method, else returns null.

Declaration

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

public Method getEnclosingMethod()

Parameters

NA

Return Value

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

Exception

NA

Getting Enclosing Method of the Underlying Class Example

The following example shows the usage of java.lang.Class.getEnclosingMethod() 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 getEnclosingMethod() method, enclosing method 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()).ClassAObject().getClass();

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

Output

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

Method = public java.lang.Object com.tutorialspoint.ClassDemo.ClassAObject()

Getting Enclosing Method of the ArrayList Class Example

The following example shows the usage of java.lang.Class.getEnclosingMethod() method. In this program, we've used class of ArrayList. Then using getEnclosingMethod(), enclosing Method 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.getEnclosingMethod());
   }
}

Output

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

null

Getting Enclosing Method of the Thread Class Example

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

package com.tutorialspoint;

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

Output

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

null
java_lang_class.htm
Advertisements