java - 将子类的集合作为父类(super class)的集合传递

标签 java

我有一个看起来或多或少像这样的 POJO:

public class Action {
    private String eventId;
    private List<ActionArgument> arguments;
    //action to perform when this action is done
    private List<Action> onCompleteActions;

    public Action() {
    }

    public Action(String eventId, List<ActionArgument> arguments, List<Action> onCompleteActions) {
        this.eventId = eventId;
        this.arguments = arguments;
        this.onCompleteActions = onCompleteActions;
    }

    public String getEventId() {
        return eventId;
    }
    public void setEventId(String eventId) {
        this.eventId = eventId;
    }
    public List<ActionArgument> getArguments() {
        return arguments;
    }
    public void setArguments(List<ActionArgument> arguments) {
        this.arguments = arguments;
    }
    public List<Action> getOnCompleteActions() {
        return onCompleteActions;
    }
    public void setOnCompleteAction(List<Action> onCompleteActions) {
        this.onCompleteActions = onCompleteActions;
    }
}

我有一个如下所示的扩展类:

public class UserDefinedAction extends Action {
    //for reordering actions with the default actions
    private String doBefore;
    private String doAfter;
    private String doAfterComplete;

    public String getDoBefore() {
        return doBefore;
    }

    public void setDoBefore(String doBefore) {
        this.doBefore = doBefore;
    }

    public String getDoAfter() {
        return doAfter;
    }

    public void setDoAfter(String doAfter) {
        this.doAfter = doAfter;
    }

    public String getDoAfterComplete() {
        return doAfterComplete;
    }

    public void setDoAfterComplete(String doAfterComplete) {
        this.doAfterComplete = doAfterComplete;
    }
}

我在其他地方有一个服务,我想这样做:

...
UserDefinedAction udAction = new UserDefinedAction();
udAction.setOnCompleteAction(new ArrayList<UserDefinedAction>());

我认为这应该可行,因为 UserDefinedAction 是一个 Action,因为它正确地扩展了它?

最佳答案

List<UserDefinedAction> 不是 List<Action> 的子类即使UserDefinedAction延伸Action .为了你可以传递 List<UserDefinedAction>为了您的服务,请更改 UserDefinedAction#setOnCompleteAction接收 List<? extends Action> 的方法, 现在你可以传递 new ArrayList<UserDefinedAction>() .

更多信息:

关于java - 将子类的集合作为父类(super class)的集合传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18136330/

相关文章:

java - 在二维数组中找到到角点的最短路径

java - 非法访问错误 : Method is inaccessible to class

java - 安卓、Java套接字

java - 休息获取: How to add "URL with Query Parameters" in Query Parameters of a URL?

java - Hadoop Java错误:线程 “main”中的异常java.lang.ClassNotFoundException:泰坦尼克号

java - 使用 JPA 的 Spring 安全性。如何配置applicationContext-security.XML文件?(使用DaoAuthenticationProvider)

java - 每次打开 eclipse 时都必须打开模拟器 3 次才能让应用程序运行

java - Android 在 ImageView 上查看图像的问题

java - 我的 Java Sieve 代码速度很慢并且无法按预期的时间复杂度进行扩展

java - jar 文件无法在 java 7 中运行,但可以在 java 6 中运行