微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java中fillInStackTrace方法中的“ int dummy”是什么意思?

如何解决Java中fillInStackTrace方法中的“ int dummy”是什么意思?

private native Throwable fillInStackTrace(int dummy);

创建异常时,用dummy=0调用方法dummy是什么意思?是构造堆栈跟踪的深度吗?

更新:

public class MyEx extends RuntimeException{
   
    @Override
    public synchronized Throwable fillInStackTrace() {
        Method method = null;
        try {
            Class<?>[] classArray = new Class<?>[1];
            classArray[0] = int.class;
            method =Throwable.class.getDeclaredMethod("fillInStackTrace",classArray);
            method.setAccessible(true);
            Object obg = method.invoke(this,6);

            StackTraceElement[] trace = ((MyEx) obg).getStackTrace();
            System.out.println();
        } catch (NoSuchMethodException e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (InvocationTargetException e) {
            e.printstacktrace();
        }
        return this;
    }
}

虚拟对象似乎真的是虚拟对象,无论我输入什么值,结果都是一样的...

我想将堆栈跟踪大小限制为3,以消耗更少的内存,而且从执行的角度来看,创建异常会更快。我有一个实际的用例,其中我需要很多异常,但是堆栈跟踪很浅。

解决方法

这没有任何意义。这是一个伪参数。

本机代码实现完全忽略该参数。例如,在OpenJDK 11中,桥接方法的实现如下:

/*
 * Fill in the current stack trace in this exception.  This is
 * usually called automatically when the exception is created but it
 * may also be called explicitly by the user.  This routine returns
 * `this' so you can write 'throw e.fillInStackTrace();'
 */
JNIEXPORT jobject JNICALL
Java_java_lang_Throwable_fillInStackTrace(JNIEnv *env,jobject throwable,jint dummy)
{
    JVM_FillInStackTrace(env,throwable);
    return throwable;
}

如您所见,dummy参数将被忽略。


如果您正在寻找一种限制堆栈跟踪深度的方法,则支持的方法是使用-XX:MaxJavaStackTraceDepth=depth选项。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。