如何从异常名称获取异常类
我有一个具有完全限定异常名称的字符串变量。我想检查 catch 块是否发生异常,无论它是否是字符串中提到的异常实例。怎么解决
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (e instanceof stringEx) { //<-- How to convert string to exception class
// do specific process
}
}
回答
也许你需要这个:
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (Class.forName(stringEx).isInstance(ex)) {
// do specific process
}
}