Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to use System.setSecurityManager() in Java

AKASH BAJWA

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 checkPermission method 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 the SecurityManager class.

Return Value

The method does not return a value.

Exceptions

  • SecurityException: setSecurityManager() returns this exception when the checkPermission() 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 libraries
import java.lang.*;
// Main Class
public class EdPresso {
    // main method
    public static void main(String[] args) {
        // Security Manager object
        SecurityManager sm = new SecurityManager();
        // set current Security Manager
        System.setSecurityManager(sm);
        // checking Security Manager
        if (System.getSecurityManager() != null){
            System.out.println("Connection is established!");
        }
        else{
            System.out.println("Connection could not established!");
        }
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring