Java类,它有自己的引用作为泛型参数

时间:2017-11-26 06:21:02

标签: java generics

我的一些接口实现方法需要返回类接口的对象。这就是我试图对接口进行建模的方法,但是将相同的类类型传递给它自己似乎是错误的:

interface Diff<T extends Diff> {
    T lessThan(T diff);
}

class ADiff implements Diff<ADiff> {
    @Override
    public ADiff lessThan(ADiff other) {
        return new ADiff();
    }
}

class BDiff implements Diff<BDiff> {
    @Override
    public BDiff lessThan(BDiff other) {
        return new BDiff();
    }
}

如果我不使用泛型,我就需要这样做:

interface Diff2{
    Diff2 lessThan(Diff2 diff2);
}
class ADiff2 implements Diff2{
    @Override
    public Diff2 lessThan(Diff2 diff2) {
        if(diff2 instanceof ADiff2)  //I want to avoid these checks
            return (ADiff2) diff2;
        else throw new RuntimeException("Unhandled");
    }
}

0 个答案:

没有答案