Bud*_*ric 6 java generics casting
我想实现一个方法,它接受一个Objectas参数,将它转换为任意类型,如果失败则返回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;
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,类强制转换异常永远不会被抛出/捕获到staticCast()函数体中.似乎Java编译器生成了一个函数,String staticCast(Object arg)在该函数中你有一条线,String result = (String) arg;即使我明确地说模板类型应该是MyClass.有帮助吗?谢谢.
Mic*_*ers 10
因为泛型类型信息在运行时被擦除,所以转换为泛型类型的标准方法是使用Class对象:
public static <T> T staticCast(Object arg, Class<T> clazz) {
if (arg == null) return null;
if (!clazz.isInstance(arg))
return null;
T result = clazz.cast(arg);
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样称呼它:
a = Main.staticCast("B", MyClass.class);
Run Code Online (Sandbox Code Playgroud)
你无法做你想做的事......至少不是这样.编译器删除了所有信息,因此你最终得到(T)作为演员中的对象 - 这是有效的.
问题是以后你正在做MyClass =(String)对象; 这是不允许的.
您绕过了编译器检查并使其在运行时失败.
那你究竟想做什么呢?如果你告诉我们你为什么要这样做,我们可能会告诉你Java的做法.
鉴于您的评论,您可以尝试以下方式:
public class Main
{
public static void main(String[] args)
{
String a;
MyClass b;
a = staticCast(new String("B"), String.class);
b = staticCast(new String("B"), MyClass.class);
System.out.println(a);
}
public static class MyClass
{
}
public static <T> T staticCast(Object arg, final Class clazz)
{
// edit - oops forgot to deal with null...
if(arg == null)
{
return (null);
}
// the call to Class.cast, as mmeyer did, might be better... probably is better...
if(arg.getClass() != clazz)
{
// Given your answer to Ben S...
return (null);
// throw new ClassCastException("cannot cast a " + arg.getClass() + " to a " + clazz);
}
return ((T)arg);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
537 次 |
| 最近记录: |