首页 > 解决方案 > 如何在 Java 中有效地进行泛型转换

问题描述

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;
    }
}

如何避免未经检查的演员表警告?

标签: javagenericscasting

解决方案


1)如果Undo专门 Command的,有Undo扩展Command:-

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

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

interface ReversibleCommand extends Command, Undo {...}

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


推荐阅读