Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are running into <a href="http://docs.oracle.com/javase/tutorial/java/generics/erasure.html" rel="nofollow">type erasure</a>. You need to add another method to the <code>interface</code> that returns the <code>Class</code> instance that relates to the type parameter <code>&lt;T&gt;</code>, this will allow you to do runtime checks on that <code>Class</code>.</p> <p>I would accomplish this thus:</p> <pre><code>public interface MyInterface&lt;T&gt; { String run( T arg ); Class&lt;T&gt; type(); } </code></pre> <p>So the <code>interface</code> returns its type. N.B. all <code>interface</code> members are <code>public</code> by default - no need for the extra <code>public</code>.</p> <pre><code>public final class SomeImplementation1 implements MyInterface&lt;String&gt; { @Override public String run(final String arg) { return arg; } @Override public Class&lt;String&gt; type() { return String.class; } } @SuppressWarnings({"unchecked"}) public static &lt;T&gt; String run(final T arg) { for (final MyInterface&lt;?&gt; element : elements) { if (element.type().isAssignableFrom(arg.getClass())) { return ((MyInterface&lt;T&gt;) element).run(arg); } } throw new IllegalArgumentException("No element found."); } </code></pre> <p>The logic is that for each <code>MyInterface</code> you check whether the argument provided is safely castable to that <code>MyInterface</code>'s <code>type()</code>. If it is then you can cast the whole <code>MyInterface</code> to the <code>arg</code>'s type. This is unchecked as the compiler cannot verify this as compile time, but as you are manually doing a check this warning can be ignored.</p> <pre><code>public static void main(String[] args) throws Exception { elements = new LinkedList&lt;&gt;(); elements.add(new SomeImplementation1()); System.out.println(run("test")); System.out.println(run(1)); } </code></pre> <p>Output:</p> <pre><code>test Exception in thread "main" java.lang.IllegalArgumentException: No element found. at com.XXX.App.run(App.java:33) at com.XXX.App.main(App.java:55) </code></pre> <p>As expected.</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