Dynamic Reflecting SignalHandler in Java
How to set up the logic for processing the if if signal sun.misc.Signal
?
Background The first generation of my code, which assumed the availability of signal processing, looked something like this:
class MyApp {
public static void main(String[] args) {
...
Signal.handle(term_sig, new SignalHandler() {
public void handle(Signal sig) { ... }
});
...
}
}
I believe I understand how to reflexively test and use signal handlers - Class.forName("sun.misc.Signal")
, reflexively call Signal.handle
, etc.
My impulse was to just instantiate another anonymous inner class with a dynamically derived class SignalHandler
, but I think this is just the desired syntax.
a source to share
To implement the SignalHandler interface, you need to use Dynamic Proxy . The rest is just a basic reflection.
Update
This is how you do it. Notice I missed the try-catch that should wrap the whole thing up.
Class<?> handlerCl = Class.forName("sun.misc.SignalHandler");
Class<?> signalCl = Class.forName("sun.misc.Signal");
Constructor signalCtor = signalCl.getConstructor(String.class);
Method signalHandle = signalCl.getMethod("handle", signalCl, handlerCl);
// Create a proxy class that implements SignalHandler
Class<?> proxyClass = Proxy.getProxyClass(signalCl.getClassLoader(),
handlerCl);
// This is used by the instance of proxyClass to dispatch method calls
InvocationHandler invHandler = new InvocationHandler()
{
public Object invoke(Object proxy,
Method method, Object[] args) throws Throwable
{
// proxy is the SignalHandler "this" rederence
// method will be the handle(Signal) method
// args[0] will be an instance of Signal
// If you're using this object for multiple signals, you'll
// you'll need to use the "getName" method to determine which
// signal you have caught.
return null;
}
};
// Get the constructor and create an instance of proxyClass
Constructor<?> proxyCtor = proxyClass.getConstructor(InvocationHandler.class);
Object handler = proxyCtor.newInstance(invHandler);
// Create the signal and call Signal.handle to bind handler to signal
Object signal = signalCtor.newInstance("TERM");
signalHandle.invoke(null, signal, handler);
a source to share