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 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用