【发布时间】:2021-08-09 20:32:24
【问题描述】:
我有以下代码:
@SuppressWarnings("unchecked")
private Class<Throwable> createClass(String className){
try {
Class<Throwable> convertedClass = (Class<Throwable>)Class.forName(className);
return convertedClass;
} catch(ClassNotFoundException | ClassCastException ex){
LOG.error("Unable to convert exception class due to exception. Skipping this whitelisted exception class, {}. Please check your configurations.",className);
LOG.error("Exception thrown while converting exception type.",ex);
return null;
}
}
本质上,我想确保转换后的类是一个例外。如果是,则返回该类,否则,返回 null。我认为通过返回Class<Throwable>,可以确保该类属于该类型,但它不是以这种方式工作的。如果我将java.lang.String 作为className 传递,我会得到Class<String> 而不是null。鉴于 Class 与 Class 不同,我预计会抛出 ClassCastException,但我认为泛型在这方面发挥了作用。有谁知道只返回 Throwable 类型的方法?
【问题讨论】: