Note that there are some explanatory texts on larger screens.

plurals
  1. POCan generics allow the Java compiler to check the type of keys and values in a map?
    text
    copied!<p>I am in a situation where I want to have a map where the keys are an interface class, and the corresponding value is a class which implements that interface. In other words the key and value type is related.</p> <p>My current implementation of the method which adds to the map, and gets an instance of the implementation class looks like:</p> <pre><code>// should be something like Class&lt;T&gt;, Class&lt;? extends T&gt; static Map&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt; map = new HashMap&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt; (); public static &lt;T&gt; void add(Class&lt;T&gt; interfaceT, Class&lt;? extends T&gt; implementationT) { map.put(interfaceT, implementationT); } public static &lt;T&gt; T get(Class&lt;T&gt; interfaceT) { // cast caused by definition not complete. Class&lt;T&gt; implementationT = (Class&lt;T&gt;) map.get(interfaceT); // try catch stuff omitted T t = implementationT.newInstance(); return t; } </code></pre> <p>My question is:</p> <p><em>Can</em> I define the "map" variable so the cast in the get(...) method is unneeded? I could not make the " new <code>HashMap&lt;Class&lt;T&gt;, Class&lt;? extends T&gt;&gt;</code>()' work, so either it is impossible or I missed something fundamental :)</p> <p>Please advise :)</p> <hr> <p>Edit: It turned out that the asSubclass() method on Class did what I wanted :D</p> <pre><code>Class&lt;?&gt; rawClassFromMap = map.get(interfaceT); Class&lt;? extends T&gt; implementationT = rawClassFromMap.asSubclass(interfaceT); </code></pre> <p>It is fine that implementationT is of type "? extends T" as I just need a T object returned.</p> <p>I like generics. Reminds me of Haskell...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload