JVM实战-掌握分派方法规则
方法调用问题
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() {// 请读者在这里填入适当的代码(不能修改其他地方的代码)// 实现调用祖父类的thinking()方法,打印"i am grandfather"}
}
Java程序中,可以通过“super”关键字很方便地调用到父类中的方法,但如何访问祖类的方法
使用MethodHandles
void thinking() {
try {MethodType mt = MethodType.methodType(void.class);Field lookupImpl = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP");lookupImpl.setAccessible(true);MethodHandle mh = ((MethodHandles.Lookup) lookupImpl.get(null)).findSpecial(GrandFather.class,"thinking", mt, GrandFather.class);mh.invoke(this);
} catch (Throwable e) {
}
}
基于栈的字节码解释执行引擎
执行引擎
基于栈的指令集与基于寄存器的指令集
Javac编译器输出的字节码指令流,基本上[1]是一种基于栈的指令集架构(Instruction SetArchitecture,ISA),字节码指令流里面的指令大部分都是零地址指令,它们依赖操作数栈进行工作。
基于栈的指令集主要优点是可移植,因为寄存器由硬件直接提供,程序直接依赖这些硬件寄存器则不可避免地要受到硬件的约束。栈架构指令集的主要缺点是理论上执行速度相对来说会稍慢一些
基于栈的解释器执行过程
示例字节码
public int calc();Code:Stack=2, Locals=4, Args_size=10: bipush 1002: istore_13: sipush 2006: istore_27: sipush 30010: istore_311: iload_112: iload_213: iadd14: iload_315: imul16: ireturn
}
操作数入栈 遇到符号出栈计算