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