开发者

How to disable System.setOut and setErr at runtime/startup?

How to prevent other classes changing the System.out? I would like to set the System.out PrintStream in App.main and make it a final so it can't be changed anymore form the other parts of the App. Is it possible? Any hacky wa开发者_运维问答y would do :)


I quick look at the code shows the SecurityManager can be used to prevent changes. ;)

public static void setErr(PrintStream err) {
    checkIO();
    setErr0(err);
}

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

You can use Thread.currentThread().getStackTrace() to identify the caller.


You can do it using your custom security manager. Implement your security manager that will throw AccessControlException if non autorized class calls it with parameter "setIO", i.e. override checkPermission(); method. Use new Throwable().getStackTrace() to identify caller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜