Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of Privileged Block in Reflection

I have seen code to get field value through Reflection executed within Privilege block. Following piece of code is taken from ReflectionUtil:

public static <T> T accessDeclaredField(final Field f, final Object o, final Class<T> responseClass) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {
        public T run() {
            boolean b = f.isAccessible();
            try {
                f.setAccessible(true);
                return responseClass.cast(f.get(o));
            } catch (SecurityException e) {
                return null;
            } catch (IllegalAccessException e) {
                return null;
            } finally {
                f.setAccessible(b);
            }
        }
    });
}

I don't understand the reason to get the field value within the privileged block; we can do it without of it.

Is it better coding practice or do we gain something extra?

Ref: API for Privileged Blocks

like image 201
Tapas Bose Avatar asked Sep 13 '14 12:09

Tapas Bose


People also ask

Does privileged block?

doPrivileged method takes an object of type java. security. PrivilegedAction and invokes its run method in privileged mode. The implementation guarantees that privileges will be revoked after the run method is executed, even if execution of doPrivileged is interrupted by an asynchronous exception.

What is privileged action?

public interface PrivilegedAction<T> A computation to be performed with privileges enabled. The computation is performed by invoking AccessController.

What is a privileged class in Java?

Privileged code is typically required only when you are writing a trusted system library (such as a Java extension package) that must read local files or perform other restricted actions, even when called by untrusted code. For example, a class that must call System.

How can Java code temporarily assume additional privileges?

Marking code as privileged enables a piece of trusted code to temporarily enable access to more resources than are available directly to the code that called it. This is necessary in some situations.


1 Answers

Without an installed Security Manager you don't need a privileged block. However, if you are writing fully general library code, which may be executed with a security manager in place, and the caller of the library may not have the needed permissions, then without a PrivilegedAction your code will be denied access as well, even though the code on its own (its CodeSource) does have the permission.

like image 86
Marko Topolnik Avatar answered Sep 22 '22 16:09

Marko Topolnik