英文:
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<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论