Skip to content

Instantly share code, notes, and snippets.

@dbroeglin
Created June 12, 2015 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbroeglin/6486db1eb4b95c891efe to your computer and use it in GitHub Desktop.
Save dbroeglin/6486db1eb4b95c891efe to your computer and use it in GitHub Desktop.
Java Proxy that exposes a management interface
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ShutdownableProxy {
public static interface Service {
public void doit();
}
public static interface Shutdownable {
public void shutdown();
}
public static class ServiceHandler implements InvocationHandler {
public void shutdown() {
System.out.println("Executing shutdown...");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
switch (method.getName()) {
case "doit":
System.out.println("Executing doit...");
break;
case "shutdown":
shutdown();
break;
}
return null;
}
}
public static Service createProxy() {
return (Service) Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), new Class[] { Service.class,
Shutdownable.class }, new ServiceHandler());
}
public static void main(String[] args) {
Service s = createProxy();
s.doit();
((Shutdownable) s).shutdown();
// less elegant and coupled to the invocation handler implementation:
((ServiceHandler) Proxy.getInvocationHandler(s)).shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment