How to use System.setSecurityManager() in Java
The static setSecurityManager() function is used to set an existing security manager. The role of the security manager class in Java is to allow applications to implement their security policies.
When this function is called, it uses the
checkPermissionmethod to perform a security check to ensure if this object has permission to change the existing security manager.
Syntax
The syntax for the setSecurityManager() function in the java.lang.System class is shown below:
void setSecurityManager(SecurityManager sm)
Parameters
setSecurityManager() takes a single value as an argument:
sm: An object of theSecurityManagerclass.
Return Value
The method does not return a value.
Exceptions
SecurityException:setSecurityManager()returns this exception when thecheckPermission()method does not allow the user to set the security manager or if the security manager has already been set.
Example
In the code snippet below, we instantiate and set the current SecurityManager. In line #13, we use the setSecurityManager() function to get the current process security manager.
// Demo code about getSecurityManager() function// Load librariesimport java.lang.*;// Main Classpublic class EdPresso {// main methodpublic static void main(String[] args) {// Security Manager objectSecurityManager sm = new SecurityManager();// set current Security ManagerSystem.setSecurityManager(sm);// checking Security Managerif (System.getSecurityManager() != null){System.out.println("Connection is established!");}else{System.out.println("Connection could not established!");}}}