Let's first understand what getEnclosingMethod()
is used for.
Example: Main.java
public class Main {
public Object getName(){
class Example{
}
return new Example();
}
public static void main(String[] args) {
Main main = new Main();
Class subClass = main.getName().getClass();
System.out.println("EnclosingMethod of Main: "
+ subClass.getEnclosingMethod());
}
}
getEnclosingMethod()
method returns the enclosing methods of this class if this class is a local class or anonymous class declared in that method or else it returns null. Since in the above example, Example Class is declared inside the method getName(), it'll return the output
EnclosingMethod of Main: public java.lang.Object Main.getName()
Meaning getName() method of Main.class has a local class Example declared.
If getName() was nothing like
public Object getName(){
return "A String";
}
getEnclosingMethod()
would return null
as no class declaration was done.
Edit: As @GhostCat mentioned , in both these examples this.getClass().getMethods()[0].getName()
will return a non-null value as you are basically calling that method.