How can you pass a List<objects that implement an interface> to a method?

北慕城南 提交于 2019-12-30 03:49:09

问题


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:

public String getAsJson(){...}

And the servlet has a bunch of mostly indentical methods that look like:

private String getUserListAsJson() {
    List<User> 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();
}

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:

public Interface JsonEnabled {
    public String getAsJson();
}

public class User implements JsonEnabled {
    ....
    @Override
    public String getAsJson() {...}
}

public class TheServlet {
    ...
    private String getUserListAsJson() {
        List<User> userList = this.dao.getUsers();
        return this.getListAsJson(userList);
    }
    private String getListAsJson(List<? implements JsonEnabled> list) {
        // The loop code that is in each method.
    }
}

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 extends and not implements 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).

I haven't found a good solution on SO or just googling around, so any help/insight would be appreciated.


回答1:


For generic wildcards the keyword extends works for both classes and interfaces:

private String getListAsJson(List<? extends JsonEnabled> list) { ... }

extends has slightly different meaning when used for defining generic bounds - it essentially translates to "is, or extends, or implements".




回答2:


Why don't just use

private String getListAsJson(List<JsonEnabled> list) { ... }

?



来源:https://stackoverflow.com/questions/10090167/how-can-you-pass-a-listobjects-that-implement-an-interface-to-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!