32leaves.net

Advanced Java generics for method arguments

Currently we’re having the semester break. During this time I work for a automotive software/hardware tool vendor. And while working there I stumbled upon a piece of code (wich was part of the API) which basically looked like this:

1
2
3
public void doSomething(ArrayList<String> list) {
    ...
}

The intention of the author was not that he wanted to have an ArrayList here, but he needed a List of String which was Serializable as well. For obvious reasons it’s not really a good idea to expect something as concrete as an ArrayList here, so there should be a better way – and there is:

1
2
3
4
public <SerializableStringList extends List<String> & Serializable>
void doSomething(SerializableStringList list) {
    ...
}

This piece of code is far better in expressing the authors intention, but still there are some drawbacks.
First of all it does not work for Java 1.4 (which might be a requirement).
The worst disadvantage is the lacking support in Eclipse. If you want to call this method, the only thing you’ll see in that little light-yellow description box is that a SerializableStringList is expected, but it won’t tell you that this is a generic type and not a real type like a class or an interface.

Still I’d prefer the later solution over the first one any time as the first one forces people to use classes they might not want to and the second solution is by far more expressive.

Leave a Reply

Fork me on GitHub