Java: How to get the caller function name

前端 未结 6 1225
情深已故
情深已故 2021-02-05 01:56

To fix a test case I need to identify whether the function is called from a particular caller function. I can\'t afford to add a boolean parameter because it would break the int

6条回答
  •  无人共我
    2021-02-05 02:56

    Another sample for android usage:

    //package your.package.name;
    import android.util.Log;
    /*
     File name: MyDebugLog.java
    */
    public class MyDebugLog {
        private static final int    index      = 4;     // <== Index in call stack array
        private static final String methodName = "Log"; // <== Name of method for public call
        private static String getCallerName() {
            String caller = "NONE";
            final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
            for (int i = 0; i < stacktrace.length; i++) {
                Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
            }
            if (stacktrace.length >= index){
                caller = stacktrace[index].getMethodName();
            }
            return caller;
        }
    
        private static String getTag() {
            String tag = "NONE";
            final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
            for (int i = 0; i < stacktrace.length; i++) {
                Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
                if (stacktrace[i].getMethodName().equals(methodName)) {
                    tag = "("+stacktrace[i + 1].getFileName() + ":" + stacktrace[i + 1].getLineNumber()+")";
                    return tag;
                }
            }
            return tag;
        }
    
        public static void Log(String message){
            Log.v(getTag(), getCallerName() + " " + message);
        }
    }
    

    Usage:

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.sample_main);
                MyDebugLog.Log("XXXXX");
        }
    

    Output:

        V/(MainActivity.java:117): onCreate XXXXX
    

    Sample of arrays:

     getTag Sample of stacktace array:
    
        Method: [0]getThreadStackTrace
        Method: [1]getStackTrace
        Method: [2]getTag
        Method: [3]Log                 <== Method for external call
        ...
     getName Sample of stacktace array:
        Method: [0]getThreadStackTrace
        Method: [1]getStackTrace
        Method: [2]getCallerName
        Method: [3]Log
        Method: [4]onCreate            <== Our external method
        Method: [5]performCreate
        ...
    

提交回复
热议问题