Java通用上限有界通配符错误

时间:2016-05-13 09:41:32

标签: java generics

我的域模型中有以下实体:

class Point {
    public String details;

    public Point() {
        details = "empty";
    }

    public Point(String details) {
        this.details = details;
    }
}

class BasicPoint<X, Y> extends Point {
    public X x;
    public Y y;

    public BasicPoint() {}

    public BasicPoint(X x, Y y) {
        this.x = x;
        this.y = y;
    }
}

class Collector<T> {
    T elem;

    public void collect(T elem) {
        this.elem = elem;
    }
}

我想对数据进行操作并将该数据作为Point或BasicPoint返回,如上所述,但编译器抱怨以下错误,尽管OUT扩展了Point:

class Operator<OUT extends Point> {
    public Collector<OUT> operate(Collector<OUT> collector) {

        // compile error, collect(OUT) cannot be applied to BasicPoint<Integer, Integer>
        collector.collect(new BasicPoint<Integer, Integer>(1,2));

        return collector;
    }
}

主要方法应如下所示:

Collector<BasicPoint<Integer, Integer>> c = new Collector<>();
c = new Operator<BasicPoint<Integer, Integer>>().operate(c);
System.out.println(c.elem.getClass() == new BasicPoint<Integer, Integer>().getClass());

2 个答案:

答案 0 :(得分:2)

您的Operator是通用的,它不能collect BasicPointOUTCollector。您可以制作abstract class Operator<OUT extends Point> { abstract Collector <OUT> operate(Collector<OUT> collector); } 摘要:

BasicPointOperator

然后class BasicPointOperator extends Operator<BasicPoint<Integer, Integer>> { @Override Collector<BasicPoint<Integer, Integer>> operate(Collector<BasicPoint<Integer, Integer>> collector) { collector.collect(new BasicPoint<Integer, Integer>(1,2)); return collector; } } 将包含您想要的实际实现:

PointOperator

class PointOperator extends Operator<Point> { @Override Collector<Point> operate(Collector<Point> collector) { collector.collect(new BasicPoint<Integer, Integer>(1,2)); return collector; } } ,这是更通用的

Private Function CheckNumber(myNumber As String) As Boolean
    Dim regex As Regex = New Regex("^07[1-9]")
    Dim match As Match = regex.Match(myNumber)
    Return match.Success
End Function

答案 1 :(得分:1)

问题在于,除非类型参数为contravariant,否则您无法将放入。像这样的东西

public Collector<?>  operate(Collector<? super Point> collector) {
    collector.collect(new BasicPoint<Integer, Integer>(1,2));
    collector.collect(new Point());

    return collector;
 }