security

Get all permissions granted to a loaded class example

With this example we are going to demonstrate how to get all permissions granted to a loaded Class in Java. In short, to get the permissions granted to a Class that is loaded you should:

  • Get the ProtectionDomain of the Class. Create a new ProtectionDomain, using the getProtectionDomain() API method of the Class.
  • Create a PermissionCollection, by getting the permissions for the specific ProtectionDomain, using the getPermissions(ProtectionDomain domain) API method of the installed Policy Object.
  • Create an Enumeration of all the Permission objects in the PermissionCollection, using the elements() API method of the PermissionCollection.
  • For each permission in the enumeration create a new Permission Object, using the nextElement() API method of the Enumeration.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.util.Enumeration;

public class GetGrantedPermissions {
 
  public static void main(String[] args) {
 
    // Get the protection domain for the class
    ProtectionDomain protectionDomain = GetGrantedPermissions.class.getProtectionDomain();

    // Get all the permissions from the Policy object
    PermissionCollection permissionCollection = Policy.getPolicy().getPermissions(protectionDomain);

    Enumeration permissions = permissionCollection.elements();
    while (permissions.hasMoreElements()) {

Permission permission = (Permission)permissions.nextElement();

System.out.println(permission.getName());
    }
  }
}

Example Output:

stopThread
exitVM
/home/kioub/workspace/test/bin/-
line.separator
java.vm.version
java.vm.specification.version
java.vm.specification.vendor
java.vendor.url
java.vm.name
os.name
java.vm.vendor
path.separator
java.specification.name
os.version
os.arch
java.class.version
java.version
file.separator
java.vendor
java.vm.specification.name
java.specification.version
java.specification.vendor
localhost:1024-
<all permissions>

 
This was an example of how to get all permissions granted to a loaded Class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button