java – How to get the name of a method as a String within the method itself?

Question:

I explain with an example what I try to achieve.

I have the following method and I want to get just (without additional information) how it is called inside the method itself.

Example with the String "foo" harcoded.

public void foo(){
    System.out.println("foo");
}

What I need is to obtain the same thing but using some internal method of the java libraries and that does not include additional information.

Answer:

You can get the name of the method by calling getMethodName() of the StackTraceElement Class.

You can even get method names in descending order of call, as the call to getAllMethods(); inside foo() :

Code:

VER DEMO EN REXTESTER

class Rextester
{  
    public static void main(String args[])
    {

        foo();
    }

    public static void foo ()
    {
        
        int intTotalMetodos = Rextester.class.getDeclaredMethods().length;
        String sMethodName = new String (Thread.currentThread().getStackTrace()[1].getMethodName());
        String sClassName  = new String (Thread.currentThread().getStackTrace()[1].getClassName());


        System.out.println("Esta clase se llama: "+sClassName+"\n");
        System.out.println("Tiene: "+intTotalMetodos+" métodos\n");

        System.out.println("Este método se llama: "+sMethodName+"\n");
        
        /*
         * Se puede obtener el nombre de métodos 
         * por orden descendente de llamada
        */
        
        getAllMethods(intTotalMetodos);        
    }


    public static void getAllMethods(int intTotalMetodos) 
    {
      int i;

      System.out.println("------------------------------------------\n");
      System.out.println("Nombres de métodos por orden descendente: \n");

      for( i = 1; i <= intTotalMetodos; i++ ) {
         System.out.println("El método "+i+" se llama: "+Thread.currentThread().getStackTrace()[i].
         getMethodName());
      }
   }
}

Result:

Esta clase se llama: Rextester

Tiene: 3 métodos

Este método se llama: foo

------------------------------------------

Nombres de métodos por orden descendente: 

El método 1 se llama: getAllMethods
El método 2 se llama: foo
El método 3 se llama: main
Scroll to Top