Why does the Java 8 generic type inference pick this overload?

前端 未结 4 788
悲哀的现实
悲哀的现实 2020-11-28 07:37

Consider the following program:

public class GenericTypeInference {

    public static void main(String[] args) {
           


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 08:12

    I ran it using Java 1.8.0_40 and got "Object".

    If you'll run the following code:

    public class GenericTypeInference {
    
    private static final String fmt = "%24s: %s%n";
    public static void main(String[] args) {
    
        print(new SillyGenericWrapper().get());
    
        Method[] allMethods = SillyGenericWrapper.class.getDeclaredMethods();
        for (Method m : allMethods) {
            System.out.format("%s%n", m.toGenericString());
            System.out.format(fmt, "ReturnType", m.getReturnType());
            System.out.format(fmt, "GenericReturnType", m.getGenericReturnType());   
       }
    
       private static void print(Object object) {
           System.out.println("Object");
       }
    
       private static void print(String string) {
           System.out.println("String");
       }
    
       public static class SillyGenericWrapper {
           public  T get() {
               return null;
           }
       }
    }
    

    You will see that you get:

    Object public T com.xxx.GenericTypeInference$SillyGenericWrapper.get() ReturnType: class java.lang.Object GenericReturnType: T

    Which explains why the method overloaded with Object is used and not the String one.

提交回复
热议问题