2

我有一个看起来或多或少像这样的 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>());

我认为这应该有效,因为UserDefinedActionIS 是Action因为它扩展了它对吗?

4

2 回答 2

5

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

更多信息:

于 2013-08-08T21:38:38.447 回答
3

UserDefinedAction可能是一个Action但一个List<Subclass>不是。正如您所定义的,您的方法必须采用 a ,因此它不能接受 a 。List<Superclass>setOnCompleteActionList<Action>List<UserDefinedAction>

于 2013-08-08T21:22:17.923 回答