[英]Java generics , bound mismatch: The type is not a valid substitute for the bounded parameter
I have a class that should return a list of objects that extend a BaseDto class. 我有一个应该返回扩展BaseDto类的对象列表的类。
So I wrote this 所以我写了这个
public class Worker<T extends BaseDto> {
private T t;
ArrayList<T> getList() {
....
}
}
and this is the object that should be returned in a list 这是应该在列表中返回的对象
public class MyDTO extends BaseDto implements Serializable {
...
}
but when I write : 但是当我写的时候:
Worker<MyDTO> q = new Worker<MyDTO>();
it doesn't compile with the following error: 它不会编译并显示以下错误:
Bound mismatch: The type MyDTO is not a valid substitute for the bounded parameter of the type Worker
绑定不匹配:MyDTO类型不是Worker类型的有界参数的有效替代品
What's wrong? 怎么了?
Worker<MyDTO> q = new Worker<MyDTO>(); // this is fine
The code you provided is supposed to work, I tried it here and it compiles normally. 您提供的代码应该可以运行,我在这里尝试过,并且可以正常编译。
However, this line will not compile in Java: 但是,此行无法在Java中编译:
Worker<BaseDto> dto = q; // this is not
Because generic types in Java are invariant , which means that two types List<X>
and List<Y>
are not compatible even if X or Y are subtypes from each other. 因为Java中的泛型类型是不变的 ,这意味着即使X或Y是彼此的子类型,两种类型的
List<X>
和List<Y>
是不兼容的。 In languages with support to covariance , this line would compile as MyDTO is a subtype of BaseDto. 在支持协方差的语言中,由于MyDTO是BaseDto的子类型,因此可以编译此行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.