Search code examples
javagenericsobserver-pattern

Java generic observer


I have 2 object: Protocol and Server. The first one is notifying Server with different objects and Server should perform action depending on type of object. So, perfect option for me is:

// Server.java
public Server implements IObserver {
    public void onAction(ActionObjectOne o) {
        //do magic
    }
    public void onAction(ActionObjectTwo o) {
        //do magic
    }
    ....
}

// Protocol.java
public Protocol extends AObservable {
   // ....
   notifyObservers(ActionObjectOne one);
   // ...
}

So i decided that it is a job for observer pattern.

public interface IObserver {
    <T extends IAction> void onAction(T action);
}

public class Server implements IObserver {
    @Override
    public <AuthAction> void onAction(AuthAction action) {
        // HERE IS A PROBLEM
    }
}

public class AuthAction extends Action; // Action implements IAction - a flag-interface

Errors are in Server:

  • The method onAction(AuthAction) of type Server must override or implement a supertype method
  • The type parameter AuthAction is hiding the type AuthAction

So, how to implement my "perfect option" =)?


Solution

  • You can do something like this:

    public void update(Observable o, Object arg) {
        try {
            Method update = getClass().getMethod("onAction", arg.getClass());
            update.invoke(this, arg);
        } catch (NoSuchMethodException e) {
            LOGGER.error("No onAction for <" + arg.getClass().getSimpleName() + "> action.");
            LOGGER.catching(e);
        } catch (Exception e) {
            LOGGER.catching(e);
        }
    }
    

    and then:

    public void onAction (AuthAction action) {
            System.out.println("New user incoming!");
        }