Note that there are some explanatory texts on larger screens.

plurals
  1. POExecute a specific parametrized class method
    primarykey
    data
    text
    <p>I have this (simplified) java interface</p> <pre><code>public interface MyInterface&lt;T&gt; { public String run( T arg ); } </code></pre> <p>and some classes that implement that interface, i.e.</p> <pre><code>public final class SomeImplementation1 implements MyInterface&lt;String&gt; { @Override public String run( String arg) { // do something with arg and return a string } } </code></pre> <p>and</p> <pre><code>public final class SomeImplementation2 implements MyInterface&lt;CustomClass&gt; { @Override public String run( CustomClass arg) { // do something with arg and return a string } } </code></pre> <p>Now, I have a global resource manager for all of those implementations, which instantiates all of them in a List for latter usage. What I would like to achieve is something like this, which obviously gives me an error</p> <pre><code>public final class MyInterfaceManager { private List&lt;MyInterface&lt;?&gt;&gt; elements = new List&lt;MyInterface&lt;?&gt;&gt;(); public MyInterfaceManager() { elements.put( new SomeImplementation1() ); elements.put( new SomeImplementation2() ); // more implementations added } // this is what I would like to achieve public &lt;T&gt; void run( T arg ) { for( MyInterface&lt;?&gt; element: elements ) { String res = element.run( arg ); // ERROR } } } </code></pre> <p>because "arg cannot be converted to capture#1 of ? by method invocation conversion". A possible solution could be to perform an <code>instanceof</code> test inside the loop, and cast the element to its real type, along with the argument as well, like that</p> <pre><code> public &lt;T&gt; void run( T arg ) { for( MyInterface&lt;T&gt; element: elements ) { if (element instanceof SomeImplementation2) { String res = ((SomeImplementation2)element).run( (CustomClass)arg ); } else if // other tests here ... } } </code></pre> <p>But i don't like it, it's not elegant at all, and it forces me to do lots of <code>instanceof</code> and casts. So, I'm wondering if there is a better way to achieve this. Thanks for your help :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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