[英]Java 8 | Using MethodHandle#invokeExact on fields dynamically
My goal is to create a MethodHandle that, by passing a class and a field name, reads that field with a MethodHandle getter and returns the value.我的目标是创建一个 MethodHandle,通过传递 class 和字段名称,使用 MethodHandle getter 读取该字段并返回值。
With this method I wanted to return an arbitrary object:使用这种方法,我想返回任意 object:
return new ConstantCallSite(MethodHandles.lookup().unreflectGetter(f).asType(MethodType.methodType(Object.class))).dynamicInvoker();
I received the Field f via Reflections.我通过 Reflections 收到了 Field f。 The problem now is that when this method is executed, the typical error for invokeExact (WrongMethodTypeException) occurs:
现在的问题是,当这个方法被执行时,典型的invokeExact(WrongMethodTypeException)错误出现了:
WrongMethodTypeException: cannot convert MethodHandle(TestClass)String to ()Object
This also applies to ints, floats, etc. In another thread I also already read that you can use invokeExact dynamically if the return of MethodHandle is changed to Object.这也适用于整数、浮点数等。在另一个线程中,我还读到如果 MethodHandle 的返回更改为 Object,您可以动态使用 invokeExact。 Here is a code snippet from the method, which makes use of passing a static final MethodHandle:
这是该方法的代码片段,它使用了传递 static 最终 MethodHandle:
return (T) handle.invokeExact(testObject);
Using MethodHandle#invoke is rather out of the question for me, as I'm after performance.使用 MethodHandle#invoke 对我来说是不可能的,因为我追求的是性能。 Without invokeExact I could possibly also fall back on using only reflections.
如果没有 invokeExact,我也可能只能使用反射。
Does anyone know a way to do this or a workaround with similar performance?有谁知道这样做的方法或具有类似性能的解决方法? The latter plays a big role in the project.
后者在该项目中起着重要作用。 I thank those in advance who could possibly help with this problem.
我提前感谢那些可能帮助解决这个问题的人。
A (non-static) getter needs an instance to retrieve the field's value from. (非静态)getter 需要一个实例来从中检索字段的值。 You should be able to make this work by adding another
Object
parameter to the erased method type:您应该能够通过将另一个
Object
参数添加到已擦除方法类型来完成此工作:
return MethodHandles.lookup().unreflectGetter(f).asType(MethodType.methodType(Object.class, Object.class));
(Also, there's no need to wrap the thing in a ConstantCallsite
) (另外,没有必要将东西包装在
ConstantCallsite
中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.