3

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?

salezica
  • 74,081
  • 25
  • 105
  • 166
  • 2
    If you go for it, make sure you provide some fallback (i.e. search for a setter/getter if you can't access the field directly.) – biziclop Feb 22 '12 at 20:22

2 Answers2

5

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.

Community
  • 1
  • 1
Luciano
  • 8,552
  • 5
  • 32
  • 56
0

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 a Constructor object for the class Class).

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.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245