Alternatives for Unsafe field access
Alan.Bateman at oracle.com
Fri Dec 9 11:59:26 UTC 2016
On 09/12/2016 07:55, Jochen Theodorou wrote:
> Maybe we have luck here and it does not apply, but if the field comes
> from a class of a module and is private, my current level knowledge of
> jigsaw says, that setAccessible will fail with an exception. It does
> not matter at all if the class with the field is exported or not. That
> is because just before the JavaOne #AwkwardStrongEncapsulation made it
> into jigsaw. Only way around this is to use the Lookup object that has
> the correct rights from the beginning. How to get it... well... there
> will be only solutions for certain types of classes.
MethodHandles.privateLookupIn  was recently added to get a Lookup
with private access, it may be useful here.
To Jochen's comments then setAccessible has been restricted for some
time to prevent it being used to break into non-exported packages. These
restriction were dialed up further as part of the JSR 376 issue that
Jochen cites. It essentially means that code cannot break into
non-public types in exported packages or non-public elements of public
types in exported packages. The new privateLookupIn specifies the same
check so that it can only be used to get private access when the target
class is in a package that is open to the caller (lookup).
None of this has any impact when doing "deep reflection" on types on the
class path, or as Jochen's modules that are declared "open" or have the
interesting types in open packages. For the short term anyway then the
restrictions will surface with code that is looking to get a non-public
elements of types in the JDK modules because the JDK modules do not open
any packages (except for jdk.unsupported which opens sun.misc and
sun.reflect to keep code using critical internal APIs working).
More information about the core-libs-dev