在 Java 8 中,给定 package 中的超类Super和 package 中a的子类Sub,b它们有一个内部类SubInner:// Super.javapackage a;public abstract class Super { private long value; protected final void setValue(long value) { this.value = value; }}//Sub.javapackage b;public class Sub extends Super { public void foo() { new SubInner().foo(); } private class SubInner { void foo() { Optional.of(1L).ifPresent(Sub.this::setValue); // Will throw IllegalAccessError at runtime. Optional.of(1L).ifPresent(t -> setValue(t)); // However, lambda works. setValue(1L); // also works. } }}我的问题是,为什么方法引用在这种情况下不起作用,而普通方法调用可以访问超类方法setValue?另外,如果我尝试这样做Sub.super::setValue,代码将无法编译,并且错误似乎与运行时错误一致:setValuehas protected access in a.Super.Exception in thread "main" java.lang.BootstrapMethodError: java.lang.IllegalAccessError: tried to access method a.Super.setValue(J)V from class b.Sub$SubInner at b.Sub$SubInner.foo(Sub.java:14) at b.Sub.foo(Sub.java:10) at b.Sub.main(Sub.java:22)Caused by: java.lang.IllegalAccessError: tried to access method a.Super.setValue(J)V from class b.Sub$SubInner at java.lang.invoke.MethodHandleNatives.resolve(Native Method) at java.lang.invoke.MemberName$Factory.resolve(MemberName.java:975) at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1000) at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1394) at java.lang.invoke.MethodHandles$Lookup.linkMethodHandleConstant(MethodHandles.java:1750) at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:477) ... 3 more
添加回答
举报
0/150
提交
取消