- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个泛型类。我知道泛型类型信息在运行时被剥离,但这是绑定(bind)类型。我认为在编译时 java.lang.Object
被绑定(bind)类型替换。如果我知道一切都至少是一个 Animal
,那么为什么编译器将它保留为 Object
?有什么我想念的东西可以使这项工作像我想要的那样吗?具体来说,main 方法中的最后一个 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
是 raw type和
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type
C
that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding toC
自从
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
然后是方法get
显示为
public Animal get() {...}
使用原始代码 Litter
类型。
至于Litter#iterator()
但是,它的返回类型是 Iterator<T>
自从
The erasure of a parameterized type (§4.5)
G<T1,...,Tn>
is|G|
.
它的删除只是Iterator
. next()
Iterator
的方法|然后被删除到
public Object next() {...}
所以很明显它的返回值不能赋值给Animal
类型的变量.
Is there something I'm missing that would make this work like I want?
不适用于原始类型,不。
关于java - 什么是有界泛型的删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42398260/
我是一名优秀的程序员,十分优秀!