开发者社区> 问答> 正文

java虚拟机有关methodHandle的代码问题?

以下代码书上说是输出“i am grandfather”,但远行实际输出为“i am father”
class Test {
class GrandFather {
void thinking() {
System.out.println("i am grandfather");
}
}
class Father extends GrandFather {
void thinking() {
System.out.println("i am father");
}
}
class Son extends Father {
void thinking() {
try {
MethodType mt = MethodType.methodType(void.class);
MethodHandle mh = lookup().findSpecial(GrandFather.class, 
"thinking", mt, getClass());
mh.invoke(this);
} catch (Throwable e) {
}
}
}
public static void main(String[] args) {
    (new Test().new Son()).thinking();
}
}

求解!

展开
收起
蛮大人123 2016-05-31 15:08:39 2657 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    个人理解是这样的:invokespecial指令用于调用一些需要特殊处理的实例方法,包括实例初始化方法、私有方法和父类方法,对应findSpecial方法返回。此处,MethodHandles.lookup().findSpecial(GrandFather.class, "thinking", mt, getClass());你需要查找的是GrandFather类型,由当前Son类型作为调用者,调用父类的thinking方法。由于Son继承自Father,而Father又继承GrandFather,所以Son本质也是一个GrandFather类型。
    那么查找GrandFather类型的thinking方法,并且是由Son作为子类调用,最终得到的方法就是Father类的thinking()
    这个方法的api是这样描述的:
    Produces an early-bound method handle for a virtual method.
    所以此方法返回的绑定GrandFather类型的thinking方法,最终是Father类的thinking()

    2019-07-17 19:22:00
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何通过 Serverless 提高 Java 微服务治理效 立即下载
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载