问题描述
在这个类中 Foo< T>
,我发现了一个奇怪的行为, 字符串
成员与 T
没有任何关系:
package test;
import java.util.ArrayList;
public class Foo< T> {
ArrayList< String>串;
T getSome(){
return null;
$ b $ p
$ b 该类用于main:
package test;
public class Main {
public static void main(){
Foo< Integer> intFoo = new Foo<>();
Integer i = intFoo.getSome();
String s1 = intFoo.strings.get(0);
Foo rawFoo = new Foo();
Object o = rawFoo.getSome();
String s2 = rawFoo.strings.get(0); //这一行的编译错误
}
}
编译错误是不兼容的类型。required:String found:Object。
看来Java忘记了 String
类型参数为 ArrayList
当使用 Foo
的原始类型时。
我的java版本是1.7.0_21
解决方案简单地说,因为 rawFoo
是非常原始的,它的非静态成员也变得生。
概述于:
$ b原始类型R的静态成员类型,它不从R的超类或超接口继承。 $ b
记下最后一个项目符号。
I have found a strange behavior when working with generics.
In this class Foo<T>
, the strings
member doesn't have anything to do with T
:
package test;
import java.util.ArrayList;
public class Foo<T> {
ArrayList<String> strings;
T getSome() {
return null;
}
}
The class is used in main:
package test;
public class Main {
public static void main() {
Foo<Integer> intFoo = new Foo<>();
Integer i = intFoo.getSome();
String s1 = intFoo.strings.get(0);
Foo rawFoo = new Foo();
Object o = rawFoo.getSome();
String s2 = rawFoo.strings.get(0); // Compilation error on this line
}
}
The compilation error is "incompatible types. required: String found: Object".
It appears that Java forgets the String
type argument to ArrayList
when raw type of Foo
is used.
My java version is 1.7.0_21
解决方案 Simply put, because rawFoo
is raw, its non-static members also become raw.
This is outlined in JLS §4.8:
Note the last bullet.
这篇关于原始类型成员丢失的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!