yan*_*nko 8 java exception-handling exception
我正在尝试从xml反序列化对象时捕获ClassCastException.
所以,
try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
Run Code Online (Sandbox Code Playgroud)
然而,这不会因为异常没有被抓住.你会建议什么?
Tom*_*ine 11
问题中的代码应该为您提供未经检查的强制警告.听听-Xlint.
所有编译器都知道T是它的边界,它可能没有(除了显式扩展Object和null类型的超级).因此,运行时的强制转换是(对象) - 不是很有用.
你可以做的是传入参数化类型的类的实例(假设它不是通用的).
class MyReader<T> {
private final Class<T> clazz;
MyReader(Class<T> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
public T restore(String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
return restoredItem;
} catch (ClassCastException exc) {
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者作为通用方法:
public <T> T restore(Class<T> clazz, String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
Run Code Online (Sandbox Code Playgroud)