java - 如何在 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;
}
}
如何避免未经检查的演员表警告?
解决方案
1)如果Undo
是专门 Command
的,有Undo
扩展Command
:-
interface Undo<I> extends Command {...}
2)否则,您可以创建第三个界面:-
interface ReversibleCommand extends Command, Undo {...}
并切换到if (command instanceof ReversibleCommand) {...}
推荐阅读
- netty - Spring WebClient 抛出 javax.net.ssl.SSLException: SSLEngine 在大量使用时已关闭
- python - TCP套接字程序多次执行相同的功能
- php - 在 Symfony 4 和 Sonata-admin 中使用 PHP-IMAP 从主机检索电子邮件
- algorithm - 带有更新的 MEX 查询
- angular - 从 AngularFirestore 获取数据从 HTML 到 TypeScript
- java - Google 的 Cloud Speech API 互联网请求的正确 URL 是什么以及如何使用 java 请求?
- three.js - Three.js 中的自我反思
- angular - 项目未从下拉列表中选择(Angular Js)
- php - 根据第一个(PHP)中的选择,使用 SQL 中的内容填充第二个选择框
- javascript - 修改Yourls书签添加功能