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
MethodHandle mh = lookup().findVirtual(GrandFather.class,"think",mt).bindTo(new GrandFather());
mh.invokeExact();
https://www.zhihu.com/question/40427344