创建适合接口和一般父类

时间:2015-06-19 14:13:26

标签: java generics reflection

我有以下方法:

private void setFilledAndAdd(Shape obj, Color col, int x, int y) {
        obj.setFilled(true);    // needs interface Fillable
        obj.setFillColor(col);
        add(obj, x, y);         // needs children of Shape (or Shape itself)
    }

如果我添加其中一行:

setFilledAndAdd(oval, color, x, y);

在行obj.setFilled(true);和行obj.setFillColor(col);中编译时间错误apears。因为Shape不是Fillable。未定义Shape类型。
更改方法setFilledAndAddFillable(不是Shape)的参数类型会导致行add(obj, x, y);中的编译时错误。在这种情况下,它需要Shape 我使用的Shape所有孩子都是Fillable。 给我一个提示,如何使这种方法有效。
感谢。

2 个答案:

答案 0 :(得分:1)

如果您可以控制ShapeFillable来源,我会重写以便所有形状都可填写,如果可以的话。您也可以使用public abstract class FillableShape extends Shape implements Fillable来继续使用类型系统。

否则,您可以使用类型转换,并通过运行时检查来确保形状是可填充的:

if(obj instanceof Fillable){
    ((Fillable) obj).setFilled(true);    
    ((Fillable) obj).setFillColor(col);
    add(obj, x, y);         
} else {
    // show an error message or something 
    // (or just draw the shape without filling it, if you want)
}

答案 1 :(得分:1)

您可以使用泛型来表示您期望具有两个特征的对象

private  <T extends Shape & Fillable> void setFilledAndAdd(T obj, Color color, int x, int y){
    obj.setFilled(true);    // needs interface Fillable
    obj.setFillColor(color);
    add(obj, x, y);
}

private void add(Shape s, int x, int y){
    // whatever code you have goes here.
}

这对我来说很好。