Java: How to get the caller function name

前端 未结 6 1159
情深已故
情深已故 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:49

    I sometimes want to make some outputs to the logcat. So I wrote a tiny class with some testing-methods:

    public class Common {
    
        // can be used as test-flag anywhere in the app (set to false, when release the app)
        public static boolean b_TEST_MODE = true;
    
        public static void echo(String message) {
            if (b_TEST_MODE) {
                StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
                // subtring(25) is to cut off app-name from output
                System.out.println(">>> " + stackTraceElements[3].toString().substring(25) + ": " + message);
            }
        }
    }
    

    now you can call it from anywhere in the app to get some infos:

    String sSQLQuery = "SELECT * FROM database WHERE id=23";
    Common.echo(sSQLQuery);
    

    The logcat prints out:

    >>> MainActivity.onCreate(MainActivity.java:46): SELECT * FROM dateabase WHERE id=23
    

提交回复
热议问题