簡體   English   中英

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

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

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

看來dummy真的是dummy,不管我放什么值,結果都是一樣的……

我想將堆棧跟蹤大小限制為 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方法,支持的方法是使用-XX:MaxJavaStackTraceDepth=depth選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM