How does Java method dispatch work with Generics a

2019-02-21 22:46发布

问题:

I ran into a situation today where Java was not invoking the method I expected -- Here is the minimal test case: (I'm sorry this seems contrived -- the 'real world' scenario is substantially more complex, and makes much more sense from a "why the hell would you do that?" standpoint.)

I'm specifically interested in why this happens, I don't care about redesign suggestions. I have a feeling this is in Java Puzzlers, but I don't have my copy handy.

See the specific question in commends within Test<T>.getValue() below:

public class Ol2 {  

    public static void main(String[] args) {  
        Test<Integer> t = new Test<Integer>() {  
            protected Integer value() { return 5; }  
        };  

        System.out.println(t.getValue());  
    }  
}  


abstract class Test<T> {  
    protected abstract T value();  

    public String getValue() {  
        // Why does this always invoke makeString(Object)?  
        // The type of value() is available at compile-time.
        return Util.makeString(value());  
    }  
}  

class Util {  
    public static String makeString(Integer i){  
        return "int: "+i;  
    }  
    public static String makeString(Object o){  
        return "obj: "+o;  
    }  
} 

The output from this code is:

obj: 5

回答1:

No, the type of value is not available at compile time. Keep in mind that javac will only compile one copy of the code to be used for all possible T's. Given that, the only possible type for the compiler to use in your getValue() method is Object.

C++ is different, because it will eventually create multiple compiled versions of the code as needed.



回答2:

Because the decision about what makeString() to use is made at compile-time and, based on the fact that T could be anything, must be the Object version. Think about it. If you did Test<String> it would have to call the Object version. As such all instances of Test<T> will use makeString(Object).

Now if you did something like:

public abstract class Test<T extends Integer> {
  ...
}

things might be different.



回答3:

Josh Bloch's Effective Java has an excellent discussion clarifying the confusion that arises because dispatch works differently for overloaded vs overridden (in a subclass) methods. Selection among overloaded methods---the subject of this question---is determined at compile time; selection among overridden methods is done at run time (and therefore gets knowledge of the specific type of the object.)

The book is much clearer than my comment: See "Item 41: Use overloading judiciously"