首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态的,反射的SignalHandler

动态的,反射的SignalHandler
EN

Stack Overflow用户
提问于 2010-05-06 18:48:05
回答 1查看 375关注 0票数 1

我如何安装信号处理逻辑当sun.misc.Signal是可用的?

假定信号处理可用的背景第一代代码如下所示:

代码语言:javascript
复制
class MyApp {
    public static void main(String[] args) {
        ...
        Signal.handle(term_sig, new SignalHandler() {
            public void handle(Signal sig) { ... }
        });
        ...
    }
}

我相信我理解如何对信号处理程序进行反射测试和使用-- Class.forName("sun.misc.Signal")、反射调用Signal.handle等等。

我的冲动只是用动态获得的SignalHandler类实例化另一个匿名内部类,但我认为这只是一厢情愿的语法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-05-06 22:45:18

您需要使用动态代理来实现SignalHandler接口。其余的只是基本的反映。

更新

这是你怎么做的。注意,我忽略了试图捕获,它需要包装所有这些。

代码语言:javascript
复制
        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's "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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2783595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档