Java 从fillInStackTrace返回的一次性文件是否安全到downcast?
如果我有Java 从fillInStackTrace返回的一次性文件是否安全到downcast?,java,exception,casting,Java,Exception,Casting,如果我有类MyException extensed Exception,那么MyException.fillInStackTrace()仍然返回Throwable,这是由于java类型系统的工作方式。将返回值强制转换为MyException是否安全?这取决于MyException.fillInStackTrace()的实现。fillInStacktrace()的示例实现 根据java消息来源: /** * Fills in the execution stack trace. This
类MyException extensed Exception
,那么MyException.fillInStackTrace()
仍然返回Throwable
,这是由于java类型系统的工作方式。将返回值强制转换为MyException是否安全?这取决于MyException.fillInStackTrace()的实现。fillInStacktrace()的示例实现
根据java消息来源:
/**
* Fills in the execution stack trace. This method records within this
* {@code Throwable} object information about the current state of
* the stack frames for the current thread.
*
* <p>If the stack trace of this {@code Throwable} {@linkplain
* Throwable#Throwable(String, Throwable, boolean, boolean) is not
* writable}, calling this method has no effect.
*
* @return a reference to this {@code Throwable} instance.
* @see java.lang.Throwable#printStackTrace()
*/
public synchronized Throwable fillInStackTrace() {
if (stackTrace != null ||
backtrace != null /* Out of protocol state */ ) {
fillInStackTrace(0);
stackTrace = UNASSIGNED_STACK;
}
return this;
}
/**
*填充执行堆栈跟踪。此方法记录在此
*{@code Throwable}有关当前状态的对象信息
*当前线程的堆栈帧。
*
*如果此{@code Throwable}{@linkplain的堆栈跟踪
*Throwable#Throwable(字符串、Throwable、布尔、布尔)不是
*可写},调用此方法无效。
*
*@返回对此{@code Throwable}实例的引用。
*@see java.lang.Throwable#printStackTrace()
*/
公共同步可丢弃fillInStackTrace(){
if(stackTrace!=null||
回溯!=null/*超出协议状态*/){
fillInStackTrace(0);
stackTrace=未分配的\u堆栈;
}
归还这个;
}
这就是为什么答案是肯定的,将返回值强制转换为MyException是安全的,除非您没有在MyException类中重写
fillInStackTrace()
方法。您尝试过吗?如果是,发生了什么?
/**
* Fills in the execution stack trace. This method records within this
* {@code Throwable} object information about the current state of
* the stack frames for the current thread.
*
* <p>If the stack trace of this {@code Throwable} {@linkplain
* Throwable#Throwable(String, Throwable, boolean, boolean) is not
* writable}, calling this method has no effect.
*
* @return a reference to this {@code Throwable} instance.
* @see java.lang.Throwable#printStackTrace()
*/
public synchronized Throwable fillInStackTrace() {
if (stackTrace != null ||
backtrace != null /* Out of protocol state */ ) {
fillInStackTrace(0);
stackTrace = UNASSIGNED_STACK;
}
return this;
}