Question

Im working on an event handling system, and i am trying to make every aspect in it automated, to do that, im trying to create a method that fires event handlers in an automatic fashion, but ive hit a wall.

Im trying to make a method that invokes methods by their parameters, i dont care about their names, or content, just their parameter types. The thing is, i dont know how to create a method that invokes certain methods by their parameter type.

A simple example to get you guys a better understanding of what im trying to accomplish.

public void invokeEvent(Event eventToBeInvoked) {

    for(Method m : listenerClass.getMethods()) {
        for(Parameter p : m.getParameters()) {
            if(p.getClass().equals(eventToBeInvoked.getClass())) {
                m.invoke(eventToBeInvoked);
            }
        }
    }
}

listenerClass is a class that contains all the methods that handle the events when they are fired, so lets say the event that was fired in the above example is DiceRollEvent which extends the Event class, a method that receives a DiceRollEvent will be invoked by the example above, like this:

public void diceRollHandler(DiceRollEvent e) {
        int turnNo = e.getTurnNumber();
        System.out.println("This is the 34th turn of the game.");
}

which will result in the end output to be: "This is the 34th turn of the game.".

This is where i've hit the wall, how do i make a class invoke methods only containing the certain parameter types?

Thank you for your assistance!

Was it helpful?

Solution

I'm not entirely sure what you're looking for, but it might be this (polymorphic method):

Inside the event handler class have a method:

public void eventHandler(Event event){
    event.handleEvent();
}

That way any class the has Event as a parent can be sent as a parameter. And then in the Event class make a method:

public void handleEvent(){
    //Do something
}

Or you can override the above method to suit the needs of every specific class that extends from Event (@override). Hope that's what you're looking for!

Edit

Or you may be looking for something like this:

public void eventHandler(DiceRollEvent event){
    //Do something
}

public void eventHandler(SomeOtherEvent event){
    //Do something
}

OTHER TIPS

Giving external system or user the right of invoking arbitrary method on arbitrary object could be dangerous and I would suggest building an API that would respect the objects for which you can invoke certain methods.

Nevertheless you can try using Reflection API. It does what you explained in the code snipped of yours.

First get a Method via:

java.lang.Class
    public Method getDeclaredMethod(String name, Class<?>... parameterTypes)

And then invoke the Method on an instance of interest.

java.lang.reflect.Method
    public Object invoke(Object obj, Object... args)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top