Method overloading and generics

2019-04-24 13:24发布

问题:

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?

回答1:

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.



回答2:

One approach I've seen is to add a dummy parameter to the less frequently used method:

public static <T> void myMethod(Class<T> klass, String bar, Void ignored) {
    System.out.println(bar);
}

calling it like

myMethod(String.class, "overloaded method", null);

but otherwise

myMethod(String.class, "overloaded method");

calls the generic method.



回答3:

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)



回答4:

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.

15.12.2.5. Choosing the Most Specific Method

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.