Reputation: 77089
To set the value of a private Field
, it needs to be marked as accessible:
field.setAccessible(true);
When will the SecurityManager not allow this? How portable is it to include this in a library? Will it fail when imported into certain contexts?
Upvotes: 3
Views: 231
Reputation: 120576
When will the SecurityManager not allow this?
The javadoc says:
First, if there is a security manager, its checkPermission method is called with a
ReflectPermission("suppressAccessChecks")
permission.A
SecurityException
is raised if flag is true but accessibility of this object may not be changed (for example, if this element object is aConstructor
object for the classClass
).
As to your other question
How portable is it to include this in a library? Will it fail when imported into certain contexts?
It is portable across JVM implementations because Field
is defined in the core library with these semantics. It is not portable across instances because different JVM instances may have differently configured security policies.
Upvotes: 0
Reputation: 8582
If you know your library won't be used inside a JVM with the Security Manager enabled, like an applet or a secured application server, then it's fine. But I would try to avoid it if possible.
There are others answers like this link that suggest there's no problem using it. So if you think it's the best approach, and the other options are too cumbersome or directly don't exist, then go ahead.
Upvotes: 5