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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With