泛型类型擦除和类型强制转换



我想遍历异常原因,直到找到"正确的原因",但看起来该类型正在被擦除,函数返回传递的异常,这导致了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);

最新更新