security

Control access to an Object example

With this example we are going to demonstrate how to control access to an Object in Java. In short, to control access to an Object you should:

  • Create a Guard, which is an object that is used to protect access to another object, with the String name of the system property, and a String of comma-separated actions granted on the property.
  • Create a GuardedObject to encapsulate the target object and the Guard object. In this example the target object is a String password.
  • In order to get the guarded object, we can invoke the getObject() API method of the GuardedObject. If the access to the object is not allowed, an AccessControlException is thrown.

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

package com.javacodegeeks.snippets.core;
 
import java.security.AccessControlException;
import java.security.Guard;
import java.security.GuardedObject;
import java.util.PropertyPermission;
 
public class ControlAccessToObject {
 
  public static void main(String[] args) {

    // The object that requires protection
    String password = new String("my_password");

    /* The permission that will protect the object. In this case everyone (thread)
	who has read access to the "java.home" environment variable can 
	access the object as well

*/
    Guard guard = new PropertyPermission("java.home", "read");

    // Create the guard
    GuardedObject guardedObject = new GuardedObject(password, guard);

    // Get the guarded object, only threads with the required permission can access the object.
    try {

 password = (String) guardedObject.getObject();
	  

 System.out.println("Protected object is " + password);
	    
    } catch (AccessControlException e) {

 System.out.println("Cannot access the object - permission is denied");
    }

  }
}

Output:

Protected object is my_password

 
This was an example of how to control access to an Object in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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