// @SuppressWarnings("unchecked")
private <T> T extractResult(Continuation continuation) {
Object result = continuation.getAttribute("result");
return (T) result;
}
它(在運行時)是否可以驗證result
可以投射到T
?Java泛型未經檢查轉換 - 可以在運行時檢查嗎?
// @SuppressWarnings("unchecked")
private <T> T extractResult(Continuation continuation) {
Object result = continuation.getAttribute("result");
return (T) result;
}
它(在運行時)是否可以驗證result
可以投射到T
?Java泛型未經檢查轉換 - 可以在運行時檢查嗎?
否。要在運行時檢查,需要一個類的實例,以便您可以使用isAssignableFrom。由於類型刪除,您無法使用T
。
不在此方法中。編譯器將刪除與T
相關的所有類型信息。
類型擦除將在運行時將T
替換爲Object
。類型信息在運行時將不存在,因此您無法檢查該類型。
它可能在運行時,但您需要一個通用類型令牌。通常你傳遞到您的泛型類型的構造函數這個
class SomeGeneric<T>
private Class<T> token;
public SomeGeneric(Class<T> token) {
this.token=token;
}
然後在你的方法,你可以在運行時檢查它
return token.cast(result) // throws ClassCastException