你怎么能传递一个 List<实现接口的对象>?方法? [英] How can you pass a List&lt;objects that implement an interface&gt; to a method?

查看:25
本文介绍了你怎么能传递一个 List<实现接口的对象>?方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多种方法的 servlet,这些方法从 DAO 获取对象列表,将列表转换为 JSON,然后在响应中将其发送回.每个列表都由具有方法的对象组成:

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:

public String getAsJson(){...}

servlet 有一堆几乎相同的方法,如下所示:

And the servlet has a bunch of mostly identical 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();
}

问题是,除了不同的 DAO 查询之外,我有大约 6 种方法(并且还在不断增加)看起来完全一样.我的想法是创建一个只有 getAsJson() 方法定义的接口,让每个 bean 实现它,然后在 servlet 中使用另一个方法来获取实现该接口的对象.最终看起来像这样:

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.
    }
}

虽然这不能编译.在从 Oracle 查找了一些文档后,对于通用参数,您只能拥有扩展而不是实现.使所有类从一个只有 getAsJson() 方法的抽象类扩展在语义上没有意义(这些类是不相关的).

That doesn't compile though. 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).

我还没有在 SO 上找到好的解决方案,或者只是在谷歌上搜索,所以任何帮助/见解将不胜感激.

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

推荐答案

对于通用通配符,关键字 extends 对类和接口都有效:

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

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

extends 用于定义泛型边界时的含义略有不同 - 它本质上翻译为是、扩展或实现".

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

这篇关于你怎么能传递一个 List<实现接口的对象>?方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆