Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method that returns different types?

I'm writing a method.

This is the Hierarchy tree:

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

The method itself looks like this:

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
}

And the usage example.

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

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

Now - as seen in the type hierarchy - there are 3 possibilities of what this method could return.

String type is defining what type of protocols shall be returned. trx.getProtocols() will return an Iterator containing ALL 3 types of protocol.

Is there a way of somehow unifying this method that it will return one of those 3 types, without using unnecessary casting later while using that method?

like image 449
dziki Avatar asked Feb 24 '26 03:02

dziki


1 Answers

You could try the following:

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)

So instead of passing the type as a string you'd pass the implementation class you want to get.

The cast (T)p is necessary but since you check for p being of type T or a subtype this is safe.

like image 51
Thomas Avatar answered Feb 25 '26 16:02

Thomas