gpt4 book ai didi

java - MethodHandle invokeExact 一个带有返回值和参数的静态方法

转载 作者:行者123 更新时间:2023-12-01 07:01:21 25 4
gpt4 key购买 nike

import java.lang.invoke.*;

public class InvokeDynamicDemo {
public static double doubleIt(double d){
System.out.print("Doubling it");
return d*2;
}

public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookUp = MethodHandles.lookup();
MethodHandle doubleIt = lookUp.findStatic(InvokeDynamicDemo.class, "doubleIt", MethodType.methodType(double.class,double.class));
doubleIt.invokeExact(2.0D); // Exception
//doubleIt.invoke(2.0D); // No exception thrown
}
}

Exception in thread "main" java.lang.invoke.WrongMethodTypeException: expected (double)double but found (double)void at java.lang.invoke.Invokers.newWrongMethodTypeException(Invokers.java:340) at java.lang.invoke.Invokers.checkExactType(Invokers.java:351) at InvokeDynamicDemo.main(InvokeDynamicDemo.java:32)

这段代码有什么问题,我不明白。请帮忙。

最佳答案

问题是您没有使用 invokeExact 方法的结果。我以前没有见过这个方法,但看起来 Java 编译器必须以一种非常特殊的方式来处理它。来自 MethodHandle documentation :

As is usual with virtual methods, source-level calls to invokeExact and invoke compile to an invokevirtual instruction. More unusually, the compiler must record the actual argument types, and may not perform method invocation conversions on the arguments. Instead, it must generate instructions that push them on the stack according to their own unconverted types. The method handle object itself is pushed on the stack before the arguments. The compiler then generates an invokevirtual instruction that invokes the method handle with a symbolic type descriptor which describes the argument and return types.

To issue a complete symbolic type descriptor, the compiler must also determine the return type. This is based on a cast on the method invocation expression, if there is one, or else Object if the invocation is an expression, or else void if the invocation is a statement. The cast may be to a primitive type (but not void).

目前,您在不使用结果的情况下调用该方法,因此编译器推断您希望它是一个 void 方法 - 因此是 (double)void 部分异常。

如果您将调用更改为:

double result = (double) doubleIt.invokeExact(2.0);

...那么编译器就知道您期望的返回类型,并可以创建适当的符号类型描述符。

关于java - MethodHandle invokeExact 一个带有返回值和参数的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47843569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com