Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find method name from within that method in Java? [duplicate]

Tags:

java

methods

I was wondering if there is a way to know the method name being executed at run time?

For instance, inside a private void doSomething (String s) method, I'd like to know that I am executing the doSomething (String s) method.

like image 699
James Raitsev Avatar asked Jan 09 '11 20:01

James Raitsev


People also ask

How do you get the method name inside the method?

Method Class | getName() Method in Java Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Return Value: It returns the name of the method, as String.

Can you call the same method within a method?

Yes you can. It is called recursion .

Does method can have the same name within the same class?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.

Can you have 2 methods with same name?

Two or more methods can have the same name inside the same class if they accept different arguments. This feature is known as method overloading.


2 Answers

Since JDK1.5, you don't need an Exception to get the StackTrace,
you can get it with Thread.currentThread().getStackTrace():

   public class Test2 {      public static void main(String args[]) {         new Test2().doit();      }      public void doit() {         System.out.println(            Thread.currentThread().getStackTrace()[1].getMethodName()); // output : doit      }    } 
like image 105
RealHowTo Avatar answered Sep 19 '22 15:09

RealHowTo


System.out.println(new Exception().getStackTrace()[0].getMethodName()); 

Also See

  • Can-i-determine-who-is-calling-a-function-or-instantiating-a-class-in-java
like image 32
jmj Avatar answered Sep 17 '22 15:09

jmj