What is the need for a Preferred Block in reflection

I saw the code for getting the field value through Reflection, executed in the Privilege block. The following 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 do not understand the reason for getting the field value in the privileged block; we can do it without it.

Is this the best coding practice, or are we getting something extra?

Link: API for privileged blocks

+5
source share
2 answers

Without a security manager installed, you do not need a privileged block. However, if you write completely general library code that can be executed with the security manager in place, and the calling library object may not have the required permissions, then without PrivilegedAction your code will also be denied access, although the code itself (its CodeSource) has resolution.

+6
source

Yes, you benefit from calling PrivilegedAction with the permissions of the calling class, even if the code (in this case, the accessDeclaredField method) is called by external code that does not have these permissions.

Without using AccessController.doPrivileged , if some X code calls the ReflectionUtils API to access the declared field, and the X code does not have suppressAccessChecks security permission, then the action will end with a security exception.

Concluding the action inside AccessController.doPrivileged , ReflectionUtils notes that its action must be performed with its own permissions, even if the calling X code does not have these permissions.

+2
source

Source: https://habr.com/ru/post/1202491/


All Articles