jdk.internal.reflect.ReflectionFactory and SecurityManager

Martin Buchholz martinrb at google.com
Mon Jan 9 21:27:18 UTC 2017


On Mon, Jan 9, 2017 at 11:29 AM, Paul Sandoz <paul.sandoz at oracle.com> wrote:

> Hi Martin,
>
> Have you tried using:
>
>  MethodHandles.privateLookupIn(ConcurrentLinkedQueue.class,
> MethodHandles.lookup()).
>     findVarHandle(…)
>
> ?
>

Thanks!  privateLookupIn was not in my toolbox.  I'm happy with:

    final VarHandle HEAD, TAIL, ITEM, NEXT;

    public WhiteBox() throws ReflectiveOperationException {
        Class<?> qClass = LinkedTransferQueue.class;
        Class<?> nodeClass = Class.forName(qClass.getName() + "$Node");
        MethodHandles.Lookup lookup
            = MethodHandles.privateLookupIn(qClass, MethodHandles.lookup());
        HEAD = lookup.findVarHandle(qClass, "head", nodeClass);
        TAIL = lookup.findVarHandle(qClass, "tail", nodeClass);
        NEXT = lookup.findVarHandle(nodeClass, "next", nodeClass);
        ITEM = lookup.findVarHandle(nodeClass, "item", Object.class);
    }

    Object head(LinkedTransferQueue q) { return HEAD.getVolatile(q); }
    Object tail(LinkedTransferQueue q) { return TAIL.getVolatile(q); }
    Object item(Object node)           { return ITEM.getVolatile(node); }
    Object next(Object node)           { return NEXT.getVolatile(node); }

although programming this way does not feel very Java-esque.  I miss being
able to use a Node type at compile time.

I agree there is some inconsistency here, and we wanted to discourage the
> use of setAccessible. One problem is setAccessible conflates accessibility
> with stomping on final fields. If we do allow setAccessible access to work
> for unreflecting i would still not want to allow VarHandles to stomp on
> final fields, so some inconsistency would remain.
>

I agree with your decision to not give unreflected VarHandles the same
unconstrained superpowers that the Field has.

My whitebox tests tend to use private access only for reading, but I can
imagine cases where it is useful to give testing code stronger access than
for regular VarHandles, maybe even to write final fields, for example for
fuzz testing or reliably creating an internal state that can only happen
with a race.  There's may be a case for providing such a big hammer, if
it's sufficiently hard to get at, but I can live without it.


> My preference would be to encourage people to use
> MethodHandles.privateLookupIn.
>

I'm a convert! It will take a while for privateLookupIn to become "common
knowledge".


More information about the core-libs-dev mailing list