获取指定类的调用位置:Thread.currentThread().getStackTrace() && new Exception().getStackTrace();

Thread.currentThread().getStackTrace()方法中使用了new Exception().getStackTrace();

public StackTraceElement[] getStackTrace() {
        if (this != Thread.currentThread()) {
            // check for getStackTrace permission
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkPermission(
                    SecurityConstants.GET_STACK_TRACE_PERMISSION);
            }
            // optimization so we do not call into the vm for threads that
            // have not yet started or have terminated
            if (!isAlive()) {
                return EMPTY_STACK_TRACE;
            }
            StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
            StackTraceElement[] stackTrace = stackTraceArray[0];
            // a thread that was alive during the previous isAlive call may have
            // since terminated, therefore not having a stacktrace.
            if (stackTrace == null) {
                stackTrace = EMPTY_STACK_TRACE;
            }
            return stackTrace;
        } else {
            // Don't need JVM help for current thread
            return (new Exception()).getStackTrace();
        }
    }
public static String getSignedCallHierarchy(Class clz) {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        if (null != stackTrace && stackTrace.length > 0) {
            StringBuilder sb = new StringBuilder();

            StackTraceElement stackTraceElement;
            String fileName;
            String className;
            String methodName;
            int lineNumber;
            for (int i = 1; i < stackTrace.length; i++) {
                stackTraceElement = stackTrace[i];
                className = stackTraceElement.getClassName();
                if (!clz.getName().equals(className)) {
                    continue;
                } else {
                    methodName = stackTraceElement.getMethodName();
                    fileName = stackTraceElement.getFileName();
                    lineNumber = stackTraceElement.getLineNumber();
                    sb.append(className).append(".").append(methodName).append("(").append(fileName).append(":").append(lineNumber).append(")");
                    break;
                }
            }
            return sb.toString();
        }
        return "";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值