[英]Java generics - unexpected situation with Optional wrapping generics
I have faced following situation: 我已经遇到以下情况:
import com.google.common.base.Optional;
public class CovarianceTest {
class Race {
}
class Dog<Race> {
}
public Optional<Dog<? extends Race>> getDog() {
Dog<? extends Race> dogWithSomeRace = new Dog();
return Optional.of(dogWithSomeRace);
}
}
Situation like this causes compilation problem. 这样的情况会导致编译问题。 The IDE says:
IDE说:
Incompatible types.
Required: Optional<Dog<? extends Race>>
Found: Optional<? extends Dog<? extends Race>
Which is clearly wrong. 这显然是错误的。
Could someone explain why this is happening? 有人可以解释为什么会这样吗?
It seems you confused the class' generic type declaration with the boundary declaration of a generic type argument. 似乎您将类的泛型类型声明与泛型类型参数的边界声明混淆了。
In your case: 在您的情况下:
class Race {}
class Dog<Race> {} // "Race" is declared as a generic type in dog. It's not referring to your Race class in any way.
Your definition of Dog
is equivalent to 您对
Dog
定义等同于
class Dog<E> {}
If you want to set a subclass of Race
to be a generic boundary for Dog
, then do for example 如果要将
Race
的子类设置为Dog
的通用边界,请执行例如
class Dog<E extends Race> {}
You could also refine the method's generic declarations: 您还可以优化方法的泛型声明:
public Optional<Dog<? extends Race>> // this could be shortend to Dog<?>, because Dog's boundary is already limited to Race in the class signature
getDog() {
Dog<? extends Race> dogWithSomeRace // This can be shortend aswell to Dog<?>
= new Dog(); // Missing type declaration in the constructor call
return Optional.of(dogWithSomeRace);
}
This is your code: 这是您的代码:
Dog<Race>
) is a type parameter that you will use for further parametrization of class Dog
. Dog<Race>
类中)是一个类型参数,将用于进一步对class Dog
进行参数化。 Dog<? extends Race> dogWithSomeRace = new Dog();
Dog<? extends Race> dogWithSomeRace = new Dog();
Dog<? extends Race> dogWithSomeRace = new Dog();
this is considered as not best practice. I believe the code below is what you are trying to do. 我相信下面的代码就是您要尝试执行的操作。 Use T as type parameter.
使用T作为类型参数。 Here we go:
开始了:
import com.google.common.base.Optional;
public class CovarianceTest {
class Race {
}
class Dog<T> {
void whatever(T t) {
System.out.println(t);
}
}
public Optional<Dog<? extends Race>> getDog() {
Dog<? extends Race> dogWithSomeRace = new Dog<Race>();
return Optional.of(dogWithSomeRace);
}
public static void main(String[] args) {
System.out.println((new CovarianceTest()).getDog().isPresent());
System.out.println((new CovarianceTest()).getDog().get().getClass());
}
}
This prints nicely: 打印效果很好:
true
真正
class CovarianceTest$Dog类CovarianceTest $ Dog
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.