Get caller Info via StackTraceElement - Java java.lang

Java examples for java.lang:Throwable

Description

Get caller Info via StackTraceElement

Demo Code



public class Main{
    private static String callerInfo() {
        return "[Caller :: " + getCaller() + "] " + timeInfo();
    }//  ww  w  .java 2  s . c  o m
    private static String getCaller() {
        String selfName = Main.class.getSimpleName();
        boolean foundSelf = false;
        StackTraceElement[] stack = Thread.currentThread().getStackTrace();
        StackTraceElement element = null;

        for (int i = 0; i < stack.length; i++) {
            String fullClass = stack[i].getClassName();
            int nameOffset = fullClass.lastIndexOf('.') + 1;
            String className = (nameOffset > 0) ? fullClass.substring(
                    nameOffset, fullClass.length()) : "";

            if (foundSelf) {
                if (!selfName.equals(className)) {
                    element = stack[i];
                    break;
                }
            } else {
                if (selfName.equals(className))
                    foundSelf = true;
            }
        }

        if (element == null)
            element = stack[stack.length - 1];

        return String.format("%s.%s", element.getClassName(),
                element.getMethodName());
    }
    private static String timeInfo() {
        return DateUtil.formatTime(System.currentTimeMillis());
    }
    public static void format(String format, Object... args) {
        System.out.format(format + "\n", args);
    }
    public static void formatTime(String format, Object... args) {
        System.out.format(timeInfo() + " : " + format + "\n", args);
    }
}

Related Tutorials