如何在Java中验证泛型转换

时间:2018-11-19 05:23:33

标签: java generics casting

interface Command<I, O> {
    O process(I i);
}

interface Undo<I> {
    void undo(I i);
}


public class CommandRunner {
    public static <I, O> O process(Command<I, O> command, I request) {
        O result = null;

        try {
            result = command.process(request);
        } catch(Exception ex) {
            if (command instanceof Undo) {
                ((Undo<I>) command).undo(request); // <-- unchecked cast
            }
        }

        return result;
    }
}

如何避免未经检查的投放警告?

1 个答案:

答案 0 :(得分:0)

1)如果Undo专业 Command,则将Undo扩展Command:-

interface Undo<I> extends Command {...}

2)否则,您可以创建第三个界面:-

interface ReversibleCommand extends Command, Undo {...}

并切换到if (command instanceof ReversibleCommand) {...}