beyondyuefei 2009-04-01 19:21 采纳率: 100%
浏览 159
已采纳

寻求帮助,一个关于java中反射的问题

public class XXX {

.........................................................
.........................................................

static {
// Add a shutdown hook to the VM if we're running JDK 1.3. When the
// thread is executed, it will call the destroy() method of the
// current connection provider. This is necessary for some connection
// providers -- especially those for in-VM Java databases.

    Runtime runtime = Runtime.getRuntime();
    Class c = runtime.getClass();
    try {
        Method m = c.getMethod("addShutdownHook", new Class[] { Thread.class } );
        m.invoke(runtime, new Object[] { new ShutdownThread() });    
    }
    catch (NoSuchMethodException nsme) {

        // Ignore -- the user might not be running JDK 1.3.
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

..................................................
...................................................

/**
* Shuts down the current connection provider. It should be called when
* the VM is exiting so that any necessary cleanup can be done.
*/

private static class ShutdownThread extends Thread {
    public void run() {
        ConnectionProvider provider = ConnectionManager.getConnectionProvider();
        if (provider != null) {
            provider.destroy();
        }
    }
}

}

我觉得 static 块内没必要用反射来注册一个钩子,直接用

Runtime.getRuntime().addShutdownHook(new ShutdownThread()); 这不就可以了么 ?

  • 写回答

1条回答 默认 最新

  • rednaxelafx 2009-04-01 20:13
    关注

    简单来说这代码是想绕开编译器的限制,让这个类在JDK 1.3或更低的版本都可以使用。如果不使用反射,则生成的代码中对addShutdownHook()方法有符号连接,类在加载的时候如果找不到那个方法就会直接失败而导致程序退出;现在则是catch住了方法不存在时的异常,然后当做什么事也没有,继续执行下去……

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真