Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to build an extensible data object and adapter pattern in Java
    text
    copied!<p>I'm trying to build an SDK using an adapter pattern. Here's what I've got so far:</p> <pre><code>interface Adapter&lt;T&gt; { void doWork(WorkUnit&lt;T&gt; unit); Class&lt;T&gt; getT(); } class WorkUnit&lt;T&gt; { public int getId() { ... } public T getExtras() { ... } } class OldWorkUnit { public &lt;T&gt; void setExtra(T data) { /* Store data in Map&lt;Class, Object&gt; */ } public &lt;T&gt; WorkUnit&lt;T&gt; toNewWorkUnit(Adapter&lt;T&gt; adapter) { /* Map.get(adapter.getT()) */ } } </code></pre> <p>There's a good amount of generics in there, but I can't know T at compile time, and there may be multiple Adapters, all with different types of T. This is meant to be exposed to third parties, so I also need as little implementation as possible in the interface implementation, and it has to be an interface (no abstract class).</p> <p>Now I want to take this and call doWork with a WorkUnit. My first pass at the code looks like this:</p> <pre><code>class FooAdapter implements Adapter&lt;FooWorkUnit&gt; { ... } OldWorkUnit w = new OldWorkUnit(); w.setExtra(new FooWorkUnit()); Adapter&lt;?&gt; a = new FooAdapter(); WorkUnit&lt;?&gt; unit = w.toNewWorkUnit(a); a.doWork(unit); </code></pre> <p>Uh oh, that doesn't compile:</p> <pre><code>The method doWork(WorkUnit&lt;capture#2-of ?&gt;) in the type Adapter&lt;capture#2-of ?&gt; is not applicable for the arguments (WorkUnit&lt;capture#4-of ?&gt;) </code></pre> <p>I know that the WorkUnit generic argument is the same type as the Adapter.doWork() generic argument, but without knowing the type I can't cast it appropriately. </p> <p>So is there a way to work my way through this?</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