Method and generic overload

Java usually prefers the usual methods to the general ones when choosing an overloaded method that can 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 a way to get Java to use the universal version?

+8
java generics overloading
source share
4 answers

No, there is no need to remove or hide a more specific overload. However, if they behave differently, they should just have different names. And if they behave the same, it doesnโ€™t matter in any case.

+3
source share

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

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

calling him

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

but otherwise

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

calls the general method.

+1
source share

Is there a way to get Java to use the universal version?

Not without deleting, renaming, or other wisely replacing the signature of the second method. (If you want to get really hacked - don't do this - use reflection to invoke the method.) This is because the Java overload resolution procedure will try to choose the most suitable method that it can.

12/15/2.5. Choosing the most specific method

If more than one member method is available and applicable to a method call, you must select it to provide a handle to send the runtime. The Java programming language uses a rule in which the most specific method is selected.

An unofficial intuition is that one method is more specific than another if any call processed by the first method can be passed to another without a compilation type error.

+1
source share

General methods allow you to use type parameters to express dependencies between types of one or more arguments of a method and / or its return type. If there is no such dependency, the general method should not be used.

(from here )

+1
source share

All Articles