gpt4 book ai didi

java - 组合和泛型

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:20:09 24 4
gpt4 key购买 nike

我正在尝试解决这种“组合 + 泛型”的情况,并使 PostCompany.send(msg) 与传递/注入(inject)类的类型兼容。

由于 Fexed 的发送方法需要字符串作为参数,而 FeexPlus 需要整数,所以我可以更改什么以允许 Fedex 和 FedexPlus 在 PostCompany 类中用作通用类型?

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 的接口(interface)方法

关于java - 组合和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51866396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com