【发布时间】:2009-03-11 17:52:35
【问题描述】:
我想实现一个将Object 作为参数的方法,将其转换为任意类型,如果失败则返回null。到目前为止,这是我所拥有的:
public static void main(String[] args) {
MyClass a, b;
a = Main.<MyClass>staticCast(new String("B"));
}
public static class MyClass {
}
public static <T> T staticCast(Object arg) {
try {
if (arg == null) return null;
T result = (T) arg;
return result;
} catch (Throwable e) {
return null;
}
}
不幸的是,类转换异常从未在staticCast() 函数的主体中抛出/捕获。 Java 编译器似乎生成了函数String staticCast(Object arg),其中有一行String result = (String) arg;,尽管我明确说模板类型应该是MyClass。有什么帮助吗?谢谢。
【问题讨论】:
-
顺便说一句,您应该只捕获 ClassCastException,而不是 Throwable。捕获 Throwable 可能会导致严重问题。