Home » Java programming language

Java Class class getEnclosingMethod() method with example

Class class getEnclosingMethod() method: Here, we are going to learn about the getEnclosingMethod() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 19, 2019

Class class getEnclosingMethod() method

  • getEnclosingMethod() method is available in java.lang package.
  • getEnclosingMethod() method is used to return a recent enclosing method of the underlying class when this Class object denotes local or anonymous class inside the method.
  • getEnclosingMethod() method is a non-static method, it is accessible with the class objects only and if we try to access the method with the class name then we will get an error.
  • getEnclosingMethod() method does not throw an exception at the time of returning Method object.


    public Method getEnclosingMethod();


  • It does not accept any parameter.

Return value:

The return type of this method is Method, it returns recently enclosing method of the underlying class when this class is local or anonymous class.

Note: When this class is not local or anonymous, null is returned.


// Java program to demonstrate the example 
// of Method getEnclosingMethod () 
// method of Class 

public class GetEnclosingMethodOfClass {
    public Object a1;
    public GetEnclosingMethodOfClass() {
        class A1 {};
        a1 = new A1();

    public Object A1() {
        class A1 {};
        return new A1();

    public static void main(String[] args) {

        // It returns the class of A1 method is 
        // GetEnclosingMethodOfClass and Method A1 is enclose in 
        // class GetEnclosingConstructorOfClass 
        Class cl = (new GetEnclosingMethodOfClass()).A1().getClass();

        System.out.print("Enclosing Method :");


Enclosing Method :public java.lang.Object GetEnclosingMethodOfClass.A1()

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.