Java jvm 虚拟机 子类调用父类,祖类方法

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();
	}
}

阅读更多
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭