问题描述
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
选项。