Home > Software engineering >  How to restrict Interface Method calls for unknown method parameters in java
How to restrict Interface Method calls for unknown method parameters in java

Time:09-24

I have an interface like given below. Can I restrict all the classes which implements this interface from calling getValue for a QueryEngine which it doesn't have implementation of. The goal is to avoid the spillover of this logic to implemented classes (as there are many abstract classes which implements this interface).

public interface Node {

    <T> T getValue(QueryEngine engine, Class<T> context);

}

Right now in the implemented class, same function looks like this

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

Alternatively any suggestions for a generic implementation with some platform-specific pluggable overrides is also welcome (as there is only one implementation)

CodePudding user response:

It is impossible what you want.

Instead you can create some root AbstactNode abstract class with this common logic. And mark method getValue as final. And seems like you want to create two functions (may be abstract functions) like getValueByQueryEngine and getValueWithoutQueryEngine.

Smth like:

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

May be useful: Why is "final" not allowed in Java 8 interface methods?

Also in this abstract class you may want to use one of collections like:

  • Set<QueryEngine> queryEngineSupportingGetValue;
  • Map<QueryEngine, BiFunction> getValueOfQueryEngineFunctions;
  • Related