Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I say "these two generic types are the same" in a map?
    text
    copied!<p>I have a method <code>toString( Object )</code> which delegates the conversion to handlers. The handlers are defined like this:</p> <pre><code>public interface IToStringService&lt;T&gt; { public String toString( T value ); } </code></pre> <p>The code looks like this:</p> <pre><code>// (1) How can I say that these two wildcards must in fact be the same type? private Map&lt;Class&lt;?&gt;, IToStringService&lt;?&gt;&gt; specialHandlers = Maps.newHashMap(); // Generic method, must accept Object (any type really) @Override public String toString( Object value ) { if( null == value ) { return "null"; } Class&lt;?&gt; type = value.getClass(); if( type.isArray() ) { return arrayToString( value ); } // (2) How can I get rid of this SuppressWarnings? @SuppressWarnings( "unchecked" ) IToStringService&lt;Object&gt; handler = (IToStringService&lt;Object&gt;) specialHandlers.get( type ); if( null != handler ) { return handler.toString( value ); } return value.toString(); } public &lt;T&gt; void addSpecialHandler( Class&lt;T&gt; type, IToStringService&lt;T&gt; handler ) { specialHandlers.put( type, handler ); } </code></pre> <p>And one implementation looks like this:</p> <pre><code>@SuppressWarnings( "rawtypes" ) // Can't add generics to "Class" or I get compile errors when calling DefaultToStringService.addSpecialHandler() :-( public class ClassToStringService implements IToStringService&lt;Class&gt; { @Override public String toString( Class value ) { return value == null ? "null" : value.getName(); } } </code></pre> <p>I have several problems here:</p> <ol> <li><p>How can I say that the handlers in the <code>specialHandlers</code> map must match the type used as the key?</p></li> <li><p>How can I use the same information inside the method to avoid casting and <code>@SuppressWarnings</code>?</p></li> <li><p>When I change <code>ClassToStringService</code> to implement <code>IToStringService&lt;Class&lt;?&gt;&gt;</code>, I get a compile error when calling <code>addSpecialHandler( Class.class, new ClassToStringService() );</code> How do I solve this?</p></li> </ol>
 

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