防止System.exit调用
生活随笔
收集整理的這篇文章主要介紹了
防止System.exit调用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在開發運行其他開發人員編寫的代碼的容器時,請謹慎防范System.exit調用。 如果開發人員無意間調用了System.exit并將其代碼部署為由您的容器運行,則它將完全降低容器進程。 可以使用SecurityManager中的checkExit函數調用來控制。
根據SecurityManager checkExit的參考 :
當前的安全管理器通過Runtime類的exit方法調用此方法。 狀態0表示成功;狀態0表示成功。 其他值表示各種錯誤。因此,任何對exit的調用都將調用此方法,并且如果我們不希望繼續進行處理,則只需拋出異常。 我們將SecurityManager定義如下:
public class StopExitSecurityManager extends SecurityManager{private SecurityManager _prevMgr = System.getSecurityManager();public void checkPermission(Permission perm){}public void checkExit(int status){super.checkExit(status);throw new ExitTrappedException(); //This throws an exception if an exit is called.}public SecurityManager getPreviousMgr() { return _prevMgr; }}現在,我們可以提供一個易于使用的CodeControl類,如下所示:
public class CodeControl {public CodeControl(){super();}public void disableSystemExit(){SecurityManager securityManager = new StopExitSecurityManager();System.setSecurityManager(securityManager) ;} public void enableSystemExit(){SecurityManager mgr = System.getSecurityManager();if ((mgr != null) && (mgr instanceof StopExitSecurityManager)){StopExitSecurityManager smgr = (StopExitSecurityManager)mgr;System.setSecurityManager(smgr.getPreviousMgr());}elseSystem.setSecurityManager(null);} }現在可以按以下方式使用CodeControl:
CodeControl control = new CodeControl(); try {control.disableSystemExit();//invoke the methods and other classes that are not allowed to call System.exit.Object ret = invokeExecute(_method, runWith, parms); } finally {//finally enable exitcontrol.enableSystemExit(); } 這樣可以防止在disable中調用方法,并允許調用System.exit,但允許您的代碼毫無問題地調用它。
翻譯自: https://www.javacodegeeks.com/2013/11/preventing-system-exit-calls.html
總結
以上是生活随笔為你收集整理的防止System.exit调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蚊子灭绝了世界会怎样 蚊子灭绝了会怎样
- 下一篇: Java Web项目的保存和刷新