title: How can you pass a List<objects that implement an interface> to a method?
body: <p>I have a servlet with several methods that get a list of objects from the DAO, turn the list into JSON, and send 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 identical 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 <code>getAsJson()</code> 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>That doesn't compile though. 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>