jeudi 4 juillet 2019

Cast java.lang.reflect.Method to java.util.function.Consumer

I'm trying to understand Java 11 more, so I'm writing some test code. Right now I'm trying to understand if there is a right way to cast Method to any of the java.util.function interfaces, for example to Consumer.

The way I found is to create a lambda adapter around the Method#invoke method:

    public void registerCallbacks(final Object annotated) {
        Class clazz = annotated.getClass();
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Callback.class)) {
                Callback registration = method.getAnnotation(Callback.class);

                List<String> warnings = new ArrayList<>(3);

                if (!Modifier.isPublic(method.getModifiers()))
                    warnings.add(String.format("Method %s must be public", method));
                if (method.getParameterCount() != 1)
                    warnings.add(String.format("Method %s must consume only one argument", method));
                if (method.getParameterCount() == 1 && !method.getParameterTypes()[0].equals(Integer.class))
                    warnings.add(String.format("Method %s must consume %s", method, Integer.class));

                if (!warnings.isEmpty()) {
                    warnings.forEach(log::warn);
                    continue;
                }

                CALLBACKS_MAPPER.registerCallback((param) -> {
                    try {
                        method.invoke(annotated, param);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        // Should not happen due to checks before.
                        log.warn(String.format("Could not invoke %s on %s with %s", method, annotated, param), e);
                    }
                });
                log.info("Registered {} as a callback", method);
            }
        }
    }


However I want to avoid writing

    CALLBACKS_MAPPER.registerCallback((param) -> {
        try {
            method.invoke(annotated, param);
        } catch (IllegalAccessException | InvocationTargetException e) {
            // Should not happen due to checks before.
            log.warn(String.format("Could not invoke %s on %s with %s", method, annotated, param), e);
        }
    });

in favor of something simpler, like

    CALLBACKS_MAPPER.registerCallback(SomeApacheLib.methodToFunction(annotated, method));

➥ So, is there a way to map old Java 1.1 reflection library to newer Java 8 functional interfaces, or it is me being stupid and the abovementioned solution with lambda is fine as it is?





Aucun commentaire:

Enregistrer un commentaire