本文介绍了投射到带有泛型的内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下代码:
public class Outer<T> {
public class Inner{
}
public static <T> Outer<T>.Inner get(){
Object o = new Object();
return (Outer<T>.Inner)o;
}
public static void main(String[] args) throws Exception {
Outer.<String>get();
}
}
此代码在Eclipse中成功编译,但无法编译在 javac
:
This code compiles successfully in Eclipse, but fails to compile in javac
:
Outer.java:10: ')' expected
return (Outer<T>.Inner)o;
^
Outer.java:10: ';' expected
return (Outer<T>.Inner)o;
^
Outer.java:10: illegal start of expression
return (Outer<T>.Inner)o;
^
3 errors
这是 javac
或Eclipse?
Is this a bug in javac
or Eclipse?
如果我将转换改为(Outer.Inner)o
它编译,虽然有一个警告:
If I change the cast to (Outer.Inner)o
it compiles, although there is a warning:
Eclipse:
Outer.Inner is a raw type. References to generic type Outer<T>.Inner should be parameterized
javac:
Outer.java:10: warning: [unchecked] unchecked conversion
found : Outer.Inner
required: Outer<T>.Inner
return (Outer.Inner)o;
^
1 warning
Javac版本 1.6.0_21
Javac version: 1.6.0_21
推荐答案
我发现这是javac编译器中一个已经修复的错误。
I have found that this is a bug in the javac compiler that has since been fixed. JDK 7b100 compiles this fine.
请参阅
这篇关于投射到带有泛型的内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!