salezica
salezica

Reputation: 77089

Java: danger in setting private member field as accessible?

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

Answers (2)

Mike Samuel
Mike Samuel

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

Upvotes: 0

Luciano
Luciano

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

Related Questions