Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can you pass a List<objects that implement an interface> to a method?
    text
    copied!<p>I have a servlet that, passed on query params, gets a list of objects from the DAO, turns the list into JSON, and sends it back in the response. Every list is made of objects that have a method:</p> <pre><code>public String getAsJson(){...} </code></pre> <p>And the servlet has a bunch of mostly indentical methods that look like:</p> <pre><code>private String getUserListAsJson() { List&lt;User&gt; userList = this.dao.getUsers(); StringBuilder builder = new StringBuilder(); builder.append('['); // loops over the list appending the value of each objects getAsJson() builder.append(']'); return builder.toString(); } </code></pre> <p>The problem is that I have about 6 methods (and growing) that look exactly like that except for different DAO queries. My idea was to create an interface that only had the definition for the getAsJson() method, make each bean implement that, and then have another method in the servlet that took objects that implemented that interface. Ended up looking like this:</p> <pre><code>public Interface JsonEnabled { public String getAsJson(); } public class User implements JsonEnabled { .... @Override public String getAsJson() {...} } public class TheServlet { ... private String getUserListAsJson() { List&lt;User&gt; userList = this.dao.getUsers(); return this.getListAsJson(userList); } private String getListAsJson(List&lt;? implements JsonEnabled&gt; list) { // The loop code that is in each method. } } </code></pre> <p>So if anyone has actually read this far =P, that doesn't compile and after looking up some documentation from Oracle, you can only have <strong>extends</strong> and not <strong>implements</strong> for generic parameters. Making all the classes extend from an Abstract Class that just has the getAsJson() method doesn't make sense semantically (the classes are unrelated).</p> <p>I haven't found a good solution on SO or just googling around, so any help/insight would be appreciated.</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