简体   繁体   English

当重载有界的泛型时,如何返回正确的类型?

[英]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很可能是LongFloatBigInteger ,都不是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM