How do I get the method name from within that method?

前端 未结 4 1810
天命终不由人
天命终不由人 2021-02-06 10:02

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

  public static String getMethodName(final int depth)
  {
    final StackT         


        
4条回答
  •  被撕碎了的回忆
    2021-02-06 10:39

    A singleton to manage logs:

    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;
    }}
    

    An example of use:

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

    The result:

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

提交回复
热议问题