通过反射的方式注入自己的ShutdownHook并清除其他HOOK

String className = "java.lang.ApplicationShutdownHooks";
Class clazz = Class.forName(className);
Field field = clazz.getDeclaredField("hooks");
field.setAccessible(true);

Thread shutdownThread = new Thread(new Runnable() {
    @Override
    public void run() {
        // TODO
    }
});
shutdownThread.setName("My-WebShutdownThread");
IdentityHashMap excludeIdentityHashMap = new ExcludeIdentityHashMap<>();
excludeIdentityHashMap.put(shutdownThread, shutdownThread);

synchronized (clazz) {
    IdentityHashMap map = (IdentityHashMap) field.get(clazz);
    for (Thread thread : map.keySet()) {
        Log.info("found shutdownHook: " + thread.getName());
        excludeIdentityHashMap.put(thread, thread);
    }

    field.set(clazz, excludeIdentityHashMap);
}

 

你可能感兴趣的:(通过反射的方式注入自己的ShutdownHook并清除其他HOOK)