Java jvm 虛擬機器 子類呼叫父類,祖類方法
阿新 • • 發佈:2019-01-30
public class TestGrandFather { class GrandFather{ public void thinking(){ System.out.println("i am grandfather"); } } class Father extends GrandFather{ public void thinking(){ System.out.println("i am father"); } } class Son extends Father{ public void thinking(){ try { //1.7 // MethodType mt = MethodType.methodType(void.class); // MethodHandle mh = MethodHandles.lookup().findSpecial(GrandFather.class, "thinking", mt, getClass()); // mh.invoke(this); //1.8 MethodType mt = MethodType.methodType(void.class); Field IMPL_LOOKUP = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP"); IMPL_LOOKUP.setAccessible(true); MethodHandles.Lookup lkp = (MethodHandles.Lookup)IMPL_LOOKUP.get(null); MethodHandle h1 = lkp.findSpecial(GrandFather.class, "thinking", mt, GrandFather.class); h1.invoke(this); } catch (Exception e) { e.printStackTrace(); } catch (Throwable e) { e.printStackTrace(); } } } public static void main(String[] args) { (new TestGrandFather().new Son()).thinking(); } }