How does java type inference work?

2019-02-18 12:11发布

问题:

Can someone please explain how the following syntax works?

public static <K, V> HashMap<K, V> getMap(){
    return new HashMap<K, V>();
}

As in, if this method was implemented in a non instantiable util class of my own this can be used as a static factory method to create map instances, right?

Map<Integer, String> myMap = MyUtil.getMap();

would then return a new HashMap with Integer keys and String values for its entries, am I right? If so, how are the types of the key and entry of map being realized by the compiler and VM?

I would really appreciate if someone could explain how Java does this.

回答1:

You ask 'how Java does this'. Java is defined in a language specification which does not dictate how the specification is implemented. So it's really up to the implementation to pick a solution. So if you really want to know how a particular compiler or interpreter implements type inference I suspect that will need to be addressed by people familiar with that tool.

If your question is really 'what are the rules' then you'll find they are explained pretty well in the specification itself, and in the Java API documentation, and in the standard Java tutorial (in decreasing levels of formality).

It's a pretty complex area with lots of knarly cases to handle - in fact it involves three processes to understand properly (reduction, incorporation and resolution). But if you are looking for a simple summary I would state it as "when instantiating a class or method, replace each generic type with the most specific type possible". In your case replacing K with Integer and V with String is the the most specific inference that makes sense.