java - 如何限制Java中未知方法参数的接口方法调用
问题描述
我有一个如下所示的界面。我可以限制实现此接口的所有类为它没有实现的 QueryEngine 调用 getValue。目标是避免此逻辑溢出到已实现的类(因为有许多抽象类实现了此接口)。
public interface Node {
<T> T getValue(QueryEngine engine, Class<T> context);
}
现在在实现的类中,相同的函数看起来像这样
public <T> T getValue(QueryEngine engine, Class<T> context) {
if (engine == QueryEngine.VALUE1) {
return getValue1CustomFunction(engine, context);
}
return getValue1CustomFunction(engine, context); //There are no other implementations right now
}
public <T> T getValue1CustomFunction(QueryEngine engine, Class<T> Context) {
final String expression = String.format(Value1_PATTERN, arguments.get(0).getValue(engine, String.class));
return queryBuilder(context, expression);
}
或者,也欢迎对具有某些特定于平台的可插入覆盖的通用实现提出任何建议(因为只有一种实现)
解决方案
你想要什么是不可能的。
相反,您可以AbstactNode
使用这种通用逻辑创建一些根抽象类。并将方法标记getValue
为最终方法。并且似乎您想创建两个函数(可能是抽象函数),例如getValueByQueryEngine
和getValueWithoutQueryEngine
。
喜欢:
public abstract class Node {
public final <T> T getValue(QueryEngine engine, Class<T> context) {
if (engine == QueryEngine.VALUE1) {
return getValueByQueryEngine(engine, context);
}
return getValueWithoutQueryEngine(engine, context);
}
protected abstract <T> T getValueByQueryEngine(QueryEngine engine, Class<T> context);
protected abstract <T> T getValueWithoutQueryEngine(QueryEngine engine, Class<T> context);
}
可能有用: 为什么 Java 8 接口方法中不允许使用“final”?
同样在这个抽象类中,您可能希望使用以下集合之一:
Set<QueryEngine> queryEngineSupportingGetValue;
Map<QueryEngine, BiFunction> getValueOfQueryEngineFunctions;
推荐阅读
- c++ - 潜在的数据竞赛是数据竞赛吗?
- r - 范围值和 geom_bar 的问题
- amcharts4 - 设置 AmChart4 XYCursor 的 X 和 Y 标签的字体大小和颜色
- android - 除了具有更高优先级内存需求的应用程序之外,还有什么可以破坏系统的活动?
- sql-server - 在 SQL Server 2008 R2 中将 Excel 指数格式转换回其文本
- java - 我应该使用什么版本的 Java 来开发我的 MOJO Maven 插件?
- android - PopupWindow内的RecyclerView,单击项目后如何关闭?
- kubernetes - GRPC::Unavailable: 14:DNS 解析失败,当尝试从 ruby 客户端连接 python 服务器时都在 kubernates 上提供服务
- node.js - 关于在 node js 中使用 sinon 进行单元测试
- javascript - 如何在页面加载的每个会话中运行一次预加载器