Home » Java programming language

Java SecurityManager checkMemberAccess() method with example

SecurityManager Class checkMemberAccess() method: Here, we are going to learn about the checkMemberAccess() method of SecurityManager Class with its syntax and example.
Submitted by Preeti Jain, on December 16, 2019

SecurityManager Class checkMemberAccess() method

  • checkMemberAccess() method is available in java.lang package.
  • In checkMemberAccess() method we access public members and classes that have similar class loaders like caller by default and in other cases, it calls checkPermission("accessDeclaredMembers") permission.
  • checkMemberAccess() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • checkMemberAccess() method may throw an exception at the time of accessing members.
    • SecurityException – This exception may throw when the calling thread does not have the right to access members.
    • NullPointerException – This exception may throw when the given first parameter is null.

Syntax:

    public void checkMemberAccess(Class cl, int type);

Parameter(s):

  • Class cl – represents the class that indication is to be operated on.
  • int type – represents the access type like PUBLIC OR DECLARED.

Return value:

The return type of this method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void checkMemberAccess(Class cl, int type)
// method of SecurityManager 

import java.lang.reflect.*;

public class CheckMemberAccess extends SecurityManager {
    public void checkMemberAccess(Class cl, int type) {
        throw new SecurityException("Restricted..");
    }

    public static void main(String[] args) {

        // By using setProperty() method is to set the policy property 
        // with security manager
        System.setProperty("java.security.policy", "file:/C:/java.policy");

        // Instantiating a CheckMemberAccess object
        CheckMemberAccess cma = new CheckMemberAccess();

        // By using setSecurityManager() method is to set the
        // security manager
        System.setSecurityManager(cma);

        // By using checkMemberAccess(Class,type) method is to check 
        // accessibility of the member
        cma.checkMemberAccess(CheckMemberAccess.class, Member.DECLARED);

        // Display the message
        System.out.println("Not Restricted..");
    }
}

Output

Exception in thread "main" java.lang.SecurityException: Restricted..
	at CheckMemberAccess.checkMemberAccess(CheckMemberAccess.java:9)
	at CheckMemberAccess.main(CheckMemberAccess.java:27)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.