Created
June 12, 2015 18:20
-
-
Save dbroeglin/6486db1eb4b95c891efe to your computer and use it in GitHub Desktop.
Java Proxy that exposes a management interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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