[英]What is the erasure of a bounded generic type?
我有一个泛型类。 我知道泛型类型信息在运行时会被剥离,但这是绑定类型。 我认为在编译时, java.lang.Object
被绑定类型替换了。 如果我知道一切都至少会是Animal
,那么为什么编译器将其保留为Object
? 有什么我想念的东西可以让它像我想要的那样工作吗? 具体来说,main方法中的last for
循环存在编译时问题。
谢谢!
public static void main( String[] args ) throws Exception {
Litter<Cat> catLitter = new Litter<>();
for( Cat cat : catLitter ) {}
Litter<Animal> animalLitter = new Litter<>();
for( Animal animal : animalLitter ) {}
Litter litter = new Litter();
for( Animal animal : litter ) {} // Type mismatch: cannot convert from element type Object to Animal
}
public class Litter<T extends Animal> implements Iterable<T>{
@Override public java.util.Iterator<T> iterator() {
return new LitterIterator();
}
class LitterIterator implements java.util.Iterator<T> {
@Override public boolean hasNext() { return false; }
@Override public T next() { return null; }
}
}
public class Animal {}
public class Dog extends Animal{}
public class Cat extends Animal{}
强制重定向:
您期望的行为将适用于类似
public class Litter<T extends Animal> implements Iterable<T>{
public T get() {return null; /* or whatever */}
...
}
和
Litter litter = ...; // raw type
Animal animal = litter.get(); // compiles fine
由于Litter
是原始类型 ,
未从其超类或超接口继承的原始类型
C
的构造函数(第8.8节), 实例方法 (第8.4节,第9.4节)或非静态字段(第8.3节)的类型是与之相对应的原始类型。在对应于C
的通用声明中删除其类型
由于
擦除类型变量(第4.4节)是擦除其最左边界。
然后方法get
出现为
public Animal get() {...}
使用原始Litter
类型进行编码。
至于Litter#iterator()
,其返回类型为Iterator<T>
,因为
参数化类型(§4.5)
G<T1,...,Tn>
的擦除为|G|
。
它的擦除只是Iterator
。 然后将Iterator
的next()
方法擦除为
public Object next() {...}
因此,显然不能将其返回值分配给Animal
类型的变量。
有什么我想念的东西可以让它像我想要的那样工作吗?
没有原始类型,没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.