Search code examples
javareflectionprivileges

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


Solution

  • 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.