interceptingsecuritymanager.java

来自「《透视Java》的源码」· Java 代码 · 共 51 行

JAVA
51
字号
package covertjava.intercept;

/**
 * <p>Custom security manager that intercepts System.exit()</p>
 * <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
 * @author Alex Kalinovsky
 * @version 1.0
 */
public class InterceptingSecurityManager extends SecurityManager {

    protected boolean exitAllowed = false;

    public InterceptingSecurityManager() {
    }

    public boolean isExitAllowed() {
        return this.exitAllowed;
    }

    public void setExitAllowed(boolean exitAllowed) {
        this.exitAllowed = exitAllowed;
    }

    public void checkExit(int status) {
        if(this.exitAllowed == false) {
            throw new SecurityException("Exit not allwoed");
        }
    }


    public static void main(String[] args) {
        InterceptingSecurityManager secManager = new InterceptingSecurityManager();
        System.setSecurityManager(secManager);
        try {
            System.out.println("Run some logic...");
            System.exit(1);
        }
        catch (Throwable x) {
            if (x instanceof SecurityException)
                System.out.println("Intercepted System.exit()");
            else
                x.printStackTrace();
        }
        System.out.println("Run more logic...");
        secManager.setExitAllowed(true);
        System.out.println("Finished");
    }


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?