vendredi 18 mars 2016

Create a No-op InvocationHandler

I'm trying to create a no-op "listener" using Java's InvocationHandler and Proxy classes. The problem I'm running into is that if the "listener" were to have a primitive return type or perhaps an array return type -not sure here- then the invocation will cause an exception. What I'd really like is for this class to have no effects.

public class EmptyListener {
  public static <T> T createEmptyListenerFor(Class<T> aInterface) throws Exception {
    return (T) Proxy.newProxyInstance(aInterface.getClassLoader(), new Class[] { aInterface }, new EmptyInvocationHandler());
  }

  private static class EmptyInvocationHandler implements InvocationHandler {
    public EmptyInvocationHandler() {}
    @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      return returnType.newInstance(); // Doesn't work for primitives 
    }
  }
}

Perhaps I'm barking up the wrong tree here. This is intended to be an easy way to create surrogate, placeholder, or Null objects, at initialization time for listener interfaces. The idea here is that this listener could be injected and prevent accidental calls to a null reference. Is there some better way to accomplish what I'm trying to do here? Or has someone written something similar in an open source project that I don't know about? I'm aware of Guava's Optional but that's not really what I want.





Aucun commentaire:

Enregistrer un commentaire