将VarHandle转换为java.lang.reflect.Field。

huangapple go评论143阅读模式
英文:

Convert VarHandle to java.lang.reflect.Field

问题

有没有一种方法可以从 VarHandle 转换为 java.lang.reflect.Field?通过 (getter/setter) MethodHandle,可以使用 MethodHandles.reflectAs(Field.class, handle)MethodHandle 转换为 Field,或者使用 lookup.unreflect{Getter|Setter}(field)Field 转换为 MethodHandle。类似地,可以使用 lookup.unreflectVarHandle(field)Field 转换为 VarHandle,但似乎没有从 VarHandle 转换为 Field 的等效方法。

英文:

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

得分: 3

确实,这样的功能似乎确实缺失。

但是从JDK 12开始,您可以通过常量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;
});

这会在VarHandle描述可访问字段时提供Field

英文:

Such a function does indeed seem to be missing.

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

Optional&lt;Field&gt; o = varHandle.describeConstable().map(d -&gt; {
    String mName = d.bootstrapMethod().methodName();
    if(mName.equals(&quot;staticFieldVarHandle&quot;) || mName.equals(&quot;fieldVarHandle&quot;)) try {
        return ((Class&lt;?&gt;)((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.

huangapple
  • 本文由 发表于 2020年10月26日 00:52:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64526330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定