java – 组合和泛型

我正在尝试解决这个“组合泛型”的情况,并使PostCompany.send(msg)与传递给类的类型兼容.

我可以更改什么以允许Fedex和FedexPlus在PostCompany类中用作泛型类型,因为Fexed的send方法需要String作为参数而FeexPlus需要Integer?

interface Poster<T> {
    void send(T msg);
}

class Fedex implements Poster<String> {

    @Override
    public void send(String msg) {
        // do something
    }
}

class FedexPlus implements Poster<Integer> {

    @Override
    public void send(Integer msg) {
        // do something
    }
}

class PostCompany<P extends Poster> {

    private final P poster;

    public PostCompany(P poster) {
        this.poster = poster;
    }

    public void send(??? msg) { // <-- Here 
        this.poster.send(msg);
    }
}

解决方法:

你错过了海报的类型

class PostCompany<T, P extends Poster<T>> {
    public void send(T msg) { // <-- Here 
        this.poster.send(msg);
    }
}

但实际上只需输入对象的类型就更好了

class PostCompany<T> {

    private final Poster<T> poster;

    public PostCompany(Poster<T> poster) {
        this.poster = poster;
    }

    public void send(T msg) { // <-- Here 
        this.poster.send(msg);
    }
}

因为您将始终使用Poster的界面方法

上一篇:c – 将类的属性泄露给它的组件


下一篇:【转】iOS开发拓展篇—静态库