gpt4 book ai didi

java - java方法可以根据条件返回值吗?

转载 作者:太空狗 更新时间:2023-10-29 22:48:19 25 4
gpt4 key购买 nike

我有一个 ICoreClient 接口(interface),AClientBClient 类实现了这个。

ICoreClient 为用户公开。

我需要在ICoreClient 接口(interface)中添加一个新方法。因此,它需要在两个客户端中实现。我不能使此方法通用,因为它具有完全不同的签名但功能相似。

我有 2 个接口(interface) xxyy

ClientA 实现 xxClientB 实现 yy

因此,我决定在 ICoreClient 中添加一个新的 testMethod,它将为我提供 xxyy 取决于客户。

我想根据条件从单个方法返回这些接口(interface)的实例。

ClientA 中:

public xx testMethod(){
return instanceof xx;
}

ClientB 中:

public yy testMethod(){
return instanceof yy;
}

ICoreClient接口(interface)应该写什么?

public zz testMethod()

我尝试放置一个虚拟接口(interface) zz(充当通用父类(super class)型)xxyy 都是实现这个。但是仍然无法在各自的客户端中公开 xxyy 的方法,因为它最终在 zz 中进行了类型转换。

这种情况有什么已知的方法吗?

编辑:如果我将返回类型设为Object,则这些接口(interface)的方法不会公开。虽然,对象包含 xxyy 的实例,

用户仍然需要将其转换为(xxyy 用户如何知道?)以使用接口(interface)中的方法。我想公开方法ClientX 而不必强制转换为 ClientAClientB...

最佳答案

编辑后您可能正在寻找 generics .你可以像这样制作你的界面

interface ICoreClient<T>{// T will be set by each class implementing this interface
T testMethod();
}

你的每个类都可以看起来像

class ClientA implements ICoreClient<xx>{
xx testMethod(){
//return xx
}
}

class ClientB implements ICoreClient<yy>{
yy testMethod(){
//return yy
}
}

关于java - java方法可以根据条件返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30613040/

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