简体   繁体   English

Java中fillInStackTrace()方法中的int dummy是什么意思?

[英]What is the meaning of `int dummy` in the fillInStackTrace() method in Java?

private native Throwable fillInStackTrace(int dummy);

This method is called with dummy=0 when an Exception is created.创建异常时,此方法以dummy=0调用。 What is the meaning of dummy ?是什么意思dummy Is it the depth of the stack trace to construct?是构建堆栈跟踪的深度吗?

Update:更新:

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;
    }
}

It seems that dummy is really dummy, it doesn't matter what value I put in, the result will be the same...看来dummy真的是dummy,不管我放什么值,结果都是一样的……

I wanted to limit the stack trace size to 3 to consume less memory and also creating exceptions would be faster from an execution point of view.我想将堆栈跟踪大小限制为 3 以消耗更少的内存,并且从执行的角度来看,创建异常也会更快。 I have a real use case where I need many exceptions but with shallow stack traces.我有一个真实的用例,我需要很多异常,但堆栈跟踪很浅。

It doesn't mean anything.这不代表什么。 It is a dummy argument.这是一个伪论证。

The native code implementation completely ignores the argument.本机代码实现完全忽略该参数。 For example, in OpenJDK 11, the bridge method implementation is as follows:例如,在 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;
}

As you can see, the dummy argument is ignored.如您所见, dummy参数被忽略。


If you are looking for a way to limit the depth of a stacktrace, the supported way to do this is to use the -XX:MaxJavaStackTraceDepth=depth option.如果您正在寻找一种限制-XX:MaxJavaStackTraceDepth=depth方法,支持的方法是使用-XX:MaxJavaStackTraceDepth=depth选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM