[英]When overloading bounded generics, how can I return the right type?
The following code gives a compilation error. 以下代码给出了编译错误。 How coud I avoid this? 我如何避免这种情况?
public class C<T> {
public T doStuff(T arg) {}
}
public class S<T extends Number> extends C<T> {
public T doStuff(T arg) {
return new Integer(0);
}
}
Thanks! 谢谢!
So this declaration is illegal because, while you've said that T
is some kind of Number
, there's no way to specifically mandate that T
is specifically an Integer
at all times. 所以,因为当你说,这个声明是非法的T
是某种 Number
,有没有办法明确强制要求T
具体为Integer
时刻。
public T doStuff(T arg) {
return new Integer(0);
}
That T
may very well be a Long
or a Float
or a BigInteger
, none of which are Integer
. T
很可能是Long
或Float
或BigInteger
,都不是Integer
。
Luckily, Number
has the intValue()
method, which allows you to get an int from any of those Number
types. 幸运的是, Number
具有intValue()
方法,该方法使您可以从任何这些Number
类型中获取一个int。 You can use that instead: 您可以改用:
public Integer doStuff(T arg) {
return new Integer(arg.intValue());
}
You are going to have to change the way your doStuff
method works in the parent class, though; 你将不得不改变你的方式doStuff
方法工作在父类,虽然, introduce a new type parameter to the method. 向该方法引入新的类型参数。
public <S> S doStuff(S arg) {
return arg;
}
Of course, this means now that the doStuff
method is unbound as well. 当然,这意味着doStuff
方法也doStuff
。 If you really wanted to keep the bounds on Number
for the entire class, you would have to have your class use the actual concrete type you cared about. 如果您真的想让整个类的Number
保持界限,则必须让您的类使用您关心的实际具体类型。
class S extends C<Integer> {
public Integer doStuff(Integer arg) {
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.