寻求帮助,一个关于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()); 这不就可以了么 ?

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