Passing Java functions as arguments and check type response

I need to pass an arbitrary Java method to another class where it will execute asynchronously. I have a feeling that I can use lambda functions as parameters of my call method, but I'm not sure that I need to create a functional interface for it. I will also need to check the type of response.

private Object foo(String method, Object...args){
    try{
        result.set( connection.invoke(method, args) );
    } catch (InterruptedException e) {

    }

    return result.get();
}

I noticed that someone wanted to do something similar here , but I need to pass an arbitrary number of arguments (BiConsumer only works on 2). I do not know how many arguments I will need to accept.

I also need to check the response type, and everything I have found so far regarding Java type checking says this is not possible. It?

+4
1

varargs :

interface Invokable extends FunctionalInterface {
    Object invoke(Object... arguments);
}

, (int β†’ Integer, long β†’ Long ..).

cast .

Object, , :

interface Argument<R> {
    // Empty interface used to mark argument types.
}

interface Invokable<R, A extends Argument<R>> extends FunctionalInterface {
    R invoke(A argument);
}

foo, . :

private <A, R> R foo(A arg) {
    if (arg != null) {
        // TODO: Use injection or a map to create a relation between Class<A> and its Invokable<A, R>.
        final Invokable<A, R> invokable = invokables.get(a.getClass());
        try {
            return invokable.invoke(arg); // Type checked result (R).
        } catch (InterruptedException e) {
            // TODO: Handle exception.
        }
    }
    return null;
}

.

+2

Source: https://habr.com/ru/post/1620671/


All Articles