簡體   English   中英

泛型類型擦除和類型轉換

[英]Generics type erasure and type cast

我想遍歷異常原因,直到找到“正確的原因”,但看起來該類型正在被擦除,並且該函數返回傳遞的異常,這導致 main 中的 ClassCastException。 這是我的代碼:

public class Main {

public static void main(String[] args) {
    Throwable e0 = new CertPathValidatorException("0");
    Throwable e1 = new CertificateException(e0);
    Throwable e2 = new CertificateException(e1);
    Throwable e3 = new CertificateException(e2);

    CertPathValidatorException cpve = Main.<CertPathValidatorException>getCauseOf(e3);
}

@Nullable
private static <Ex extends Exception> Ex getCauseOf(final Throwable e) {
    Throwable cause = e;
    while (true) {
        try {
            return (Ex) cause;
        }
        catch (ClassCastException cce) {
            cause = cause.getCause();
        }
    }
}

}

有沒有辦法讓這個功能保持通用,或者我應該放棄這個想法?

在這里使用泛型是危險的。 Java 在編譯時解析泛型類型。 在您的代碼中,您需要在運行時進行解析。 此外,您還可以通過將類作為參數傳遞給您的函數來實現。

private static <Ex extends Exception> Ex getCauseOf(final Class<Ex> typeResolve, final Throwable e) {
    Throwable cause = e;
    while (cause != null) {
        if (typeResolve.isInstance(cause)) return (Ex) cause; // or typeResolve.cast(cause);
        else cause = cause.getCause();
    }
    return null;
}

這樣,您可以按如下方式修改調用:

CertPathValidatorException cpve = Main.getCauseOf(CertPathValidatorException.class, e3);

暫無
暫無

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

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