使用通配符参数执行方法

时间:2016-03-13 18:05:36

标签: java generics

我目前正在为具有通用参数的个人项目做一个小型工作流引擎。

这不详细,目的是用泛型做点什么。

WorkflowExecutor是将执行我的工作流程的所有步骤的类

public class WorkflowExecutor<U extends WorkflowCommand<T>, T extends WorkflowArgumentWrapper> {
    List<U> commands = new ArrayList<U>();

    public WorkflowExecutor<U, T> addCommand(U command) {
        commands.add(command);
        return this;
    }

    public void execute(T arg) {
        for(int i = 0; i < commands.size(); i++) {
            arg = commands.get(i).perform(arg);
        }
    }
}

WorkflowCommand类是我工作流程的一个步骤:

public abstract class WorkflowCommand<T extends WorkflowArgumentWrapper> {
    public abstract T perform(T arg);
}

WorkflowArgumentWrapper是传递给工作流的所有步骤的类。所以基本上这个对象将被工作流步骤修改并传递到下一步。

public class WorkflowArgumentWrappable {
}

最后是一个工作流容器(将来应该是一个单身人士)。它包含我的所有工作流程,我可以从那里执行它们:

公共类WorkflowContainer {

    private Map<WorkflowType , WorkflowExecutor<? extends WorkflowCommand<? extends WorkflowArgumentWrapper>,? extends WorkflowArgumentWrapper>> executors =
            new HashMap<WorkflowType , WorkflowExecutor<? extends WorkflowCommand<? extends WorkflowArgumentWrapper>, ? extends WorkflowArgumentWrapper>>();

    public static enum WorkflowType {
        TEST
    }

    public void init() {
        executors.put(WorkflowType.TEST, new WorkflowExecutor<WorkflowHelloWorldCmd, WorkflowHelloWorldArgument>())
            .addCommand(new WorkflowHelloWorldCmd())  // PROBLEM HERE
            .addCommand(new WorkflowHelloWorldCmd()); // PROBLEM HERE
    }

    public void execute(WorkflowType type, WorkflowArgumentWrapper arg) {
        executors.get(type).execute(arg); // PROBLEM HERE
    }
}

使用:

public class WorkflowHelloWorldCmd extends WorkflowCommand<WorkflowHelloWorldArgument> {
    @Override
    public WorkflowHelloWorldArgument perform(WorkflowHelloWorldArgument arg) {
        System.out.println(arg.getCount() + " : " + arg.getSentence());
        arg.setCount(arg.getCount() + 1);
        return arg;
    }
}

public class WorkflowHelloWorldArgument implements WorkflowArgumentWrapper {
    private String sentence;
    private int count;

    public WorkflowHelloWorldArgument()  {
        this.sentence = "Hello world";
        this.count = 0;
    }

    public String getSentence() {
        return sentence;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }
}

将命令添加到执行程序时出现问题:'addCommand(capture<? extends tbetous.workflow.WorkflowCommand<? extends tbetous.workflow.WorkflowArgumentWrapper>>)' in 'tbetous.workflow.WorkflowExecutor' cannot be applied to '(tbetous.test.WorkflowHelloWorldCmd)'

我对executors.get(type).execute(arg);感到有疑问,因为'execute(capture<? extends workflow.WorkflowArgumentWrapper>)' in 'workflow.WorkflowExecutor' cannot be applied to '(workflow.WorkflowArgumentWrapper)'

我完全坚持这一点。有办法做我想要的吗?提前谢谢你的帮助。

0 个答案:

没有答案