I was looking at a way to optimize some things in our code base with generic functions. There is a function with return type List<Object> which could have return type List<SpecifiedType>.
Bellow is a minimalist version of that function called function. It takes a parameter type, based on it calls a corresponding function (here limited to String) or generic function.
public static ArrayList<String> forString(){
ArrayList<String> res = new ArrayList<>();
// Fetching and processing data specific to String
return res;
}
public static <T> ArrayList<T> forGeneric(Class<T> type){
ArrayList<T> res = new ArrayList<>();
// Fetching data
return res;
}
public static <T> ArrayList<T> function(Class<T> type){
if(type == String.class)
return (ArrayList<T>) forString();
return forGeneric(type);
}
The target is for function above to be called like this: ArrayList<SomeType> someTypes = function(SomeType.class);
Two things I've noticed about the code above:
Cast to
ArrayList<T>is required even though we know that if typeStringis passed as a parameter it will returnArrayList<String>just likeforString()methodCast to
ArrayList<T>givesUnchecked castwarning, even though the return type will beArrayList<String>
My question is is there some better way to do so (preferably without the casts) and if not, then why
forStringandforGenericreturn the same thing (after type erasure). Maybe you could extend the example to make clear what the actual goal should be? - Marco13forString" methods are doing additional thing specific for the type they return. - Miku