How to get a method name from this method?

I am trying to create a function that returns the method name from this method:

public static String getMethodName(final int depth) { final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); return ste[ste.length - 1 - depth].getMethodName(); } 

However, when I call this method from Activity.onCreate (), it returns "main" instead of "onCreate".

How to get the actual method name from this method?

+6
java android reflection
source share
4 answers
 return ste[1+depth].getMethodName(); 

If you change the return statement as described above, you will get the name of the immediate method, the depth of the course should be zero.

+8
source share

Although throwing an Exception is a more expensive way, I will do it anyway.

 Log.d("CurrentMethod", new Exception().getStackTrace()[0].getMethodName()); 

It works if called in onCreate.

+3
source share

The syntax for managing logs is:

 public class ActiveLog { public static final String TAG = "TRACE LOG"; private static ActiveLog instance; private static boolean actif; public static ActiveLog getInstance() { if (null == instance) instance = new ActiveLog(); return instance; } private ActiveLog() { ActiveLog.setActif(true); } public void log() { if(isActif()) Log.d(TAG, "" + (new Exception().getStackTrace()[1].getClassName()) + ": " + (new Exception().getStackTrace()[1].getMethodName())); } public static boolean isActif() { return actif; } public static void setActif(boolean actif) { ActiveLog.actif = actif; }} 

Usage example:

 public class MyTest { public void test() { ActiveLog.getInstance().log(); } } 

Result:

 09-05 14:37:09.822: D/TRACE LOG(XXXX): com.TestProject.MyTest: test 
+2
source share

I think your problem is, maybe you are moving up the stack upside down. In the returned element of value 0, the most recent call (which will be getStackTrace ()). I think you intend to do the following:

 public static String getMethodName(final int depth) { final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); return ste[1 + depth].getMethodName(); } 

This will result in access to the most recent call on the stack (outside of the getStackTrace () call). For example, if you have a method:

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

This will print "foo" with the above function implementation. Of course, you can also add some check on the bounds of the function, since it can easily go beyond the array.

+1
source share

All Articles