I am writing a method in Java:
List<Foo> computeFooList() { }
I would like to write a second method with exactly the same logic, but with a different return type:
List<String> computeStringList() { }
I am trying to find a simple way to minimize the amount of re-code between these two methods. The logical difference is that when adding an object to the returned list, the first method adds acutal Foo :
List<Foo> computeFooList() { List<Foo> toReturn = ... ... for (Foo foo : ) { if () { toReturn.add(foo); } } ... return toReturn; }
and the second adds a String representation of Foo :
List<String> computeStringList() { List<String> toReturn = ... ... for (Foo foo : ) { if () { toReturn.add(foo.toString()); } } ... }
In fact, it is not so simple. I do not want to add Foo to toReturn unless I'm sure it is there. As a result, this decision is made using auxiliary functions. With two different versions of methods, I will need different versions of auxiliary functions - in the end, I would write two sets of the same type of methods, but for one small generic type.
Can I write one method that contains all the decision logic, but can generate either List<Foo> or List<String> ? Is it possible to do this without using the raw types of List (wrong practice in generics of the earth!) Or wildcard List<?> Types? I imagine an implementation that looks something like this:
List<Foo> computeFooList() { return computeEitherList(, Foo.class); } List<String> computeStringList() { return computeEitherList(, String.class); } private List<???> computeEitherList(, Class<?> whichType) { }
Is there any beautiful, elegant way to do this? I played with generic methods, but I see no way to do this. Even the reflection cheating didn’t get anywhere (maybe I need something like TypeToken ? ... eww).