2
为什么我不能在包含的本地类中引用通用父类的类型参数?如何在本地类中使用通用父类型的类型参数?
public class IsGeneric<T> {
public void doSomething(T arg) {
class A {
T x;
}
A foo = new A();
foo.x = arg;
T bar = foo.x; // error: found java.lang.Object, required T
}
}
根据Eclipse的上面的代码是完全正常的,但1.6.0_11的javac似乎觉得foo.x
是java.lang.Object类型的。一种解决方法的问题显然是使A
通用本身,如下面的代码:
public class IsGeneric<T> {
public void doSomething(T arg) {
class A<S> {
S x;
}
A<T> foo = new A<T>();
foo.x = arg;
T bar = foo.x;
}
}
不过,我想了解有什么不好的第一变体。有任何想法吗?
我知道它在C#中是一样的,但是在C#中,您也可以使用'class A',并保存在第二个泛型参数中。 –
2009-08-20 09:14:11
由于C#甚至没有本地类,它绝对不是在C#中。 – 2009-08-20 09:21:41
...类中的类与Java中的类基本不同。 – 2009-08-20 09:22:18