首页 > 解决方案 > 如何限制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);
    }

或者,也欢迎对具有某些特定于平台的可插入覆盖的通用实现提出任何建议(因为只有一种实现)

标签: javagenerics

解决方案


你想要什么是不可能的。

相反,您可以AbstactNode使用这种通用逻辑创建一些根抽象类。并将方法标记getValue为最终方法。并且似乎您想创建两个函数(可能是抽象函数),例如getValueByQueryEnginegetValueWithoutQueryEngine

喜欢:

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;

推荐阅读