Thursday, 19 November 2015

How to get the name of the current executing method in java?

Using reflection:

/** using reflection trace. */
Method method = new Object(){}.getClass().getEnclosingMethod();
String methodName = method.getName();

However, a new anonymous inner class will be created during compile time (e.g. MethodNameTest$1.class). So this will create a .class file for each method that deploys this trick.

Advantage of trick is that getEncosingMethod()

It returns java.lang.reflect.Method which can be used to retrieve all other information of the method including annotations and parameter names. This makes it possible to distinguish between specific methods with the same name (method overload).

Using stackTrace:

/** using stack trace. */
String nameUsingTrace = stackTrace[1].getMethodName();

import java.lang.reflect.Method;

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

     private static void checkMethodName() {
           /** using stack trace. */
           StackTraceElement[] stackTrace =                 
           String nameUsingTrace = stackTrace[1].getMethodName();
           System.out.println("print method name using stack trace : "
                     + nameUsingTrace);

           /** using reflection trace. */
           Method method =
                 new Object(){}.getClass().getEnclosingMethod();

           String methodName = method.getName();

           System.out.println("print method name using reflection : "
                     + methodName);
print method name using stack trace : checkMethodName
print method name using reflection : checkMethodName

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...