Java typically prefers normal methods to generic ones when choosing which overloaded method is correct, which could generate the following sscce:
public class GenericsTest {
public static void main(String[] args) {
myMethod(Integer.class, 10);
myMethod(String.class, "overloaded method");
}
public static <T> void myMethod(Class<T> klass, T foo) {
System.out.println("hello world");
}
public static <T> void myMethod(Class<T> klass, String bar) {
System.out.println(bar);
}
}
Output:
hello world
overloaded method
Is there any way to force Java to use the Generic version?
Not without removing, renaming, or other wise changing the signature of the second method. (If you want to get really hacky – don't do this – use reflection to invoke the method.) That's because Java's overload resolution procedure will try to pick the most-specific method it can.
No, not short of deleting or hiding the more specific overload. Yet, if they behave differently, they should simply have different names. And if they behave the same, it should not matter either way.
Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used.
(from here)
One approach I've seen is to add a dummy parameter to the less frequently used method:
calling it like
but otherwise
calls the generic method.