vendredi 16 octobre 2020

Invoking methods with parametrized arguments

i'm currently building an event system to handle some events in my application. The EventDispatcher calls methods with parameters, which are assignable from the event's class. This works fine with non-parametrized parameters but i cant find a solution to do this with parametrized arguments.
How can i filter for those too?

Here is a small snippet from my Dispacher:

private final Event event; // custom Event-class
private final Map<Object, List<Method>> subscriber;

/* snip */

@Override
public void run() {
    subscriber.forEach((sub, methods) -> methods.stream()
            // filter for matching event methods
            .filter(m -> {
                // returns true, even if generic types do not match
                return m.getParameters()[0].getType().isAssignableFrom(event.getClass());
            })
            .forEach(m -> {
                try {
                    m.invoke(sub, event);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    LOGGER.error("...", e);
                }
            }));
}

Note: the given methods in the subscriber map already have the required return type,1 parameter and the Annotation to identify event-methods.

EDIT: From the comments: The problem is, that Java returns true, when I check for Event<Integer> isAssignableFrom( Event<String> )





Aucun commentaire:

Enregistrer un commentaire