简体   繁体   English

泛型类型擦除和类型转换

[英]Generics type erasure and type cast

I want to travel down the exception causes until I find "the right one", but it looks like the type is being erased and the function returns the passed exception which results in ClassCastException in main.我想遍历异常原因,直到找到“正确的原因”,但看起来该类型正在被擦除,并且该函数返回传递的异常,这导致 main 中的 ClassCastException。 Here is my code:这是我的代码:

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

}

Is there a way to keep this function generic, or should I abandon this idea?有没有办法让这个功能保持通用,或者我应该放弃这个想法?

Using generics here is dangerous.在这里使用泛型是危险的。 Java resolves generic types at compile time. Java 在编译时解析泛型类型。 In your code, you would require a resolve at runtime.在您的代码中,您需要在运行时进行解析。 You can do so by passing a class as parameter to your function in addition.此外,您还可以通过将类作为参数传递给您的函数来实现。

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

This way, you can modify the call as following:这样,您可以按如下方式修改调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM