I have a list of Foo and Bar objects, and a converter for each of the corresponding ones.
public static void Convert(Foo1 a, Bar1 b) {
...
}
public static void Convert(Foo2 a, Bar2 b) {
...
}
etc
Some of the objects, however, contains lists.
The Convert-methods needs to be different, because Bar1 is vastly different from Bar2 and Bar3 and so on, but I want to create one method to handle all possible lists.
Is it possible to create a generic method that calls the appropriate non-generic method depending on the contents of the list?
So far I’ve tried this:
public static <T, S> void ConvertList(List<T> list, List<S> libList) {
list = new ArrayList<T>(libList.size());
for (int i = 0; i < libList.size(); ++i) {
Convert(list.get(i), libList.get(i));
}
}
But that doesn’t compile because “Cannot resolve method ‘Convert(T,S)'”
Any ideas?
No, you can’t do this – overloading is determined at compile-time, and it sounds like you want different methods to be called based on either the execution-time type of the objects involved, or at least on the execution-time type of
T, which is completely unknown at execution time.Code-path decisions based on execution-time type are usually handled via overriding via overloading, but it’s not clear whether this is feasible in this case. If you could put an appropriate
convertmethod in eachFoo??subclass, you could potentially constrainTandSaccordingly, but basically there’s too much context we’re unaware of at the moment.You could use reflection to find and invoke the most appropriate method at execution time, but that’s going to be painful to code and potentially significantly slower.