About Me

My photo
Bangalore, Karnataka, India
Showing posts with label Restricting access of public methods to only specific classes in Java. Show all posts
Showing posts with label Restricting access of public methods to only specific classes in Java. Show all posts

Wednesday, March 24, 2010

Allowing only defined classes to access the method in Java

If you wonder how do you allow only a specific class to be allowed to access your method. Here you go. You can check the class name on the stack and do take a decision whether you allow are reject permission to.

Class callerClass = Reflection.getCallerClass(2); //2 stack position
If(!validList_.contains(callerClass)) {
Throw new IllegalAccessException(); or SecurityException();
}

In the above snippet validList is list of classes you wish to allow. This is barrowed from the sun.misc.Unsafe classe.