内部类的构造函数引用在运行时失败,并显示验证错误
2022-09-03 07:41:31
我正在使用lambda为内部类构造函数创建一个供应商。IntelliJ建议我把它改成。SpectatorSwitcher是我正在工作的类的非静态内部类。建议的代码编译良好(使用maven),但我在执行时得到以下VerifyError:ctx -> new SpectatorSwitcher(ctx)
SpectatorSwitcher::new
Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
Exception Details:
Location:
Test.lambda$runTest$8(LTest$Worker;)V @2: invokedynamic
Reason:
Type 'Test$Worker' (current frame, stack[1]) is not assignable to 'Test'
Current Frame:
bci: @2
flags: { }
locals: { 'Test$Worker' }
stack: { 'Test$Worker', 'Test$Worker' }
Bytecode:
0000000: 2a2a ba00 0b00 00b6 000c b1
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2688)
at java.lang.Class.getMethod0(Class.java:2937)
at java.lang.Class.getMethod(Class.java:1771)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
为什么javac / maven在编译时没有失败,但仍然产生无效的字节代码?
编辑:问题似乎比简单的调用复杂得多,这是重现它所需的代码:
import java.util.function.Function;
/**
* @author Yawkat
*/
public class Test {
public static void main(String[] args) { new Test().runTest(); }
private void runTest() {
Worker worker = new Worker();
run(() -> worker.print(field -> new SomeClass(field)));
run(() -> worker.print(SomeClass::new));
}
private void run(Runnable runnable) {
runnable.run();
}
private class SomeClass {
final Object field;
SomeClass(Object field) {
this.field = field;
}
}
private static class Worker {
void print(Function<Object, Object> i) {
System.out.println(i.apply(null));
}
}
}