Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i make this work with java generics
    text
    copied!<p>Suppose I have this interfaces and concretes:</p> <pre><code>public interface MeterValue {} public class MeterValueA implements MeterValue {} public class MeterValueB implements MeterValue {} public interface ReportBuilder&lt;T extends MeterValue&gt; {} public class ReportBuilderA implements ReportBuilder&lt;MeterValueA&gt; {} public class ReportBuilderB implements ReportBuilder&lt;MeterValueB&gt; {} </code></pre> <p>And I have a global instance: </p> <pre><code>ReportBuilder&lt;MeterValue&gt; reportBuilder; </code></pre> <p>I would like to vary the reportBuilder instance as follows:</p> <pre><code>if (isA()) reportBuilder = new ReportBuilderA(); else reportBuilder = new ReportBuilderB(); reportBuilder.desiredMethod(); </code></pre> <p>Doing this I get "Type Missmatch". How can I get my desired functionality? Or how could I improve my class design to be more flexible?</p> <p><strong>Edit:</strong></p> <p>The wildcard ? solved the problem. But also introduced other problems. Say i have this methods in the interface:</p> <pre><code>public interface ReportBuilder&lt;T extends MeterValue&gt; { public String getStuff(List&lt;T&gt; values); } public class ReportBuilderA implements ReportBuilder&lt;MeterValueA&gt; { @Override public String getStuff(List&lt;MeterValueA&gt; values) { return "A"; } } public class ReportBuilderB implements ReportBuilder&lt;MeterValueB&gt; { @Override public String getStuff(List&lt;MeterValueB&gt; values) { return "B"; } } </code></pre> <p>Say I have this instance:</p> <pre><code> ReportBuilder&lt;? extends MeterValue&gt; reportBuilder = new ReportBuilderA(); </code></pre> <p>And:</p> <pre><code> List&lt;? extends MeterValue&gt; list = new ArrayList&lt;MeterValueA&gt;(); String s = reportBuilder.getStuff(list); </code></pre> <p>The call to getStuff(...) will not work since list contain wildcards. One fix would be to modify the ReportBuilder interface method to: </p> <pre><code>public String getStuff(List&lt;? extends MeterValue&gt; values); </code></pre> <p>But then I break the concrete ReportBuilders. (list is also a global instance where the content may vary)</p> <p>Any ideas?</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