java多态之继承

来源:互联网 发布:深圳大数据公司 编辑:程序博客网 时间:2024/06/09 21:04
public class GrandFatherCaller {    class GrandFather{        void thinking(){            System.out.println("i am grandfather");        }    }    class Father extends GrandFather{        void thinking(){//            System.out.println("i am father");            try {                MethodType mt = MethodType.methodType(void.class);                MethodHandle mh = lookup().findSpecial(                        GrandFather.class, "thinking", mt, Father.class);                mh.invoke(this);            } catch (Throwable throwable) {                throwable.printStackTrace();            }        }    }    class Son extends Father{        void thinking(){            try {                MethodType mt = MethodType.methodType(void.class);                MethodHandle mh = lookup().findSpecial(   //它只能调用到传给findSpecial()方法的最后一个参数(“specialCaller”)的直接父类的版本                        GrandFather.class, "thinking", mt, Son.class);                mh.invoke(this);            } catch (Throwable throwable) {                throwable.printStackTrace();            }        }    }    public static void main(String[] args) {        (new GrandFatherCaller().new Son()).thinking();    }}

讲解:

  1. 用到了反射的知识
  2. MethodHandle mh = lookup().findSpecial( //它只能调用到传给findSpecial()方法的最后一个参数(“specialCaller”)的直接父类的版本
原创粉丝点击