java - 返回不同类型的方法?

标签 java collections iterator

我正在写一个方法。

这是层次结构树:

IProtocoll
|
|--ProtocolImpl1
|
|--ProtocolImpl2
|
|--ProtocolImpl3

方法本身是这样的:

public static List<IProtocol> getProtocolsByType(String type, Transaction trx) {
    Iterator<IProtocol> protocols = trx.getProtocols();
    List<IProtocol> protocolsList = new ArrayList<IProtocol>();
    while (protocols.hasNext()) {
        if (StringHeper.isEqual(protocolls.next().getProtocolType(), type) {
            protocolsList.add(protocolls.next());
        }
    }
    return protocolsList
}

以及用法示例。

List<IProtocol> list = ProtocolHelper.getrProtocolsByType("PROTOCOL1", trx)

for (IProtocol protocol : list) {
    ProtocolHelper.createProtocolType1((ProtocolImpl1) protocol)
}

现在 - 如类型层次结构中所示 - 此方法可能返回 3 种可能性。

String type 定义应返回什么类型的协议(protocol)。 trx.getProtocols() 将返回一个包含所有 3 种协议(protocol)类型的迭代器。

有没有办法以某种方式统一此方法,使其返回这 3 种类型中的一种,而无需在以后使用该方法时使用不必要的转换?

最佳答案

您可以尝试以下方法:

public static <T extends IProtocol> List<T> getProtocolsByType(Class<T> typeClass, Transaction trx) {    
  Iterator<IProtocol> protocols = trx.getProtocols();
  List<T> protocolsList = new ArrayList<T>();
  while( protocols.hasNext() ) {
     //call next() only once
     IProtocol p = protocols.next();

     //Check if p is an instance of typeClass or a subtype
     if ( typeClass.isAssignableFrom( p.getClass() ) {
        protocolsList.add( (T)p );
     }
   }
   return protocolsList;
}

List<ProtocolImpl1> list = ProtocolHelper.getrProtocolsByType( ProtocolImpl1.class, trx)

因此,不是将类型作为字符串传递,而是传递您想要获取的实现类。

强制转换 (T)p 是必要的,但由于您检查 p 是否属于 T 类型或子类型,因此这是安全的。

关于java - 返回不同类型的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371977/

相关文章:

java - 在 Java 中从键值对构建映射

C++ 无法访问由 vector 的迭代器返回的类中的公共(public)属性

java - ArrayList 最后一个索引

c++ - 制作可用于初始化 vector 的迭代器

java - Java中的MSCAPI证书选择框;太阳MSCAPI?

java - 从 USB 端口读取数据

java - 高效插入长值集合

java - Applet 不通过 ImageIO.write 创建图像文件

java - 如果超时或处理消息的应用程序崩溃,消息会发生什么情况?

caching - 构建集合缓存是一个好习惯吗?