【问题标题】:How to disable System.setOut and setErr at runtime/startup?如何在运行时/启动时禁用 System.setOut 和 setErr?
【发布时间】:2011-11-15 13:46:16
【问题描述】:

如何防止其他类更改 System.out?我想在 App.main 中设置 System.out PrintStream 并使其成为最终版本,这样就不能再从应用程序的其他部分更改它了。可能吗?任何骇人听闻的方式都可以:)

【问题讨论】:

    标签: java logging io outputstream


    【解决方案1】:

    我快速查看代码显示 SecurityManager 可用于防止更改。 ;)

    public static void setErr(PrintStream err) {
        checkIO();
        setErr0(err);
    }
    
    private static void checkIO() {
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("setIO"));
        }
    }
    

    您可以使用 Thread.currentThread().getStackTrace() 来识别调用者。

    【讨论】:

      【解决方案2】:

      您可以使用自定义安全管理器来完成此操作。实现您的安全管理器,如果非自动化类使用参数“setIO”调用它将抛出 AccessControlException,即覆盖 checkPermission(); 方法。使用new Throwable().getStackTrace() 识别来电者。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-23
        • 2020-08-18
        • 1970-01-01
        • 1970-01-01
        • 2021-06-29
        相关资源
        最近更新 更多