import java.lang.invoke.MethodHandle;
import static java.lang.invoke.MethodHandles.lookup;
import java.lang.invoke.MethodType;public 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 ()
{

// System.out.println("I am son");
try {
MethodType mt = MethodType.methodType(void.class);
MethodHandle mh = lookup().findSpecial(GrandFather.class, "thinking",mt , getClass());
mh.invoke(this);
} catch (Throwable e) {
// TODO: handle exception
}

}

}

public static void main(String[] args) {
(new Test().new Son()).thinking();

}

}
代码如上所示,书上说输出应为I am grandfather,而我的实际输出为I am father

解决方案 »

  1.   

    https://www.zhihu.com/question/40427344这里有解决
      

  2.   

    MethodType mt = MethodType.methodType(void.class);
                MethodHandle mh = lookup().findVirtual(GrandFather.class,"think",mt).bindTo(new GrandFather());
                mh.invokeExact();
      

  3.   

    应该是jdk版本变更导致的无法获取跟父类方法导致。这个问题网上查一下,会有详细的说明。
      

  4.   

    这个问题可以移步知乎R大的回答:
    https://www.zhihu.com/question/40427344