将子类的集合作为超类的集合传递

时间:2013-08-08 21:19:36

标签: 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因为它正确延伸了吗?

2 个答案:

答案 0 :(得分:4)

即使List<UserDefinedAction>扩展List<Action>

UserDefinedAction 也不是 Action的子类。为了将List<UserDefinedAction>传递给您的服务,请更改UserDefinedAction#setOnCompleteAction方法以接收List<? extends Action>,现在您可以传递new ArrayList<UserDefinedAction>()

更多信息:

答案 1 :(得分:3)

您的UserDefinedAction可能是Action,但List<Subclass> List<Superclass>。正如您所定义的那样,您的setOnCompleteAction方法必须使用List<Action>,因此无法接受List<UserDefinedAction>