Convert VarHandle to java.lang.reflect.Field

Viewed 207

Is there any way to convert from a VarHandle to a java.lang.reflect.Field? With a (getter/setter) MethodHandle, one can use MethodHandles.reflectAs(Field.class, handle) to go from MethodHandle to Field or lookup.unreflect{Getter|Setter}(field) to go from Field to MethodHandle. Similarly, one can use lookup.unreflectVarHandle(field) to go from Field to VarHandle, but there doesn't seem to be any equivalent way to go from VarHandle to Field.

1 Answers

Such a function does indeed seem to be missing.

But starting with JDK 12, you can emulate it via the constant API:

Optional<Field> o = varHandle.describeConstable().map(d -> {
    String mName = d.bootstrapMethod().methodName();
    if(mName.equals("staticFieldVarHandle") || mName.equals("fieldVarHandle")) try {
        return ((Class<?>)((ClassDesc)d.bootstrapArgsList().get(0))
            .resolveConstantDesc(MethodHandles.lookup()))
            .getDeclaredField(d.constantName());
    } catch (ReflectiveOperationException ex) {}
    return null;
});

This provides the Field when the VarHandle is describing an accessible field.

Related