全部文件 2个类1个节口:如下图
MapleClass MapleClassProxy MapleInterface 具体代码:
package com.luyo.MapleTest; /** * Created by Administrator on 2016/11/15. */ public interface MapleInterface { public void method1(); public void method2(); public void method3(); } package com.luyo.MapleTest; /** * Created by Administrator on 2016/11/15. */ public class MapleClass implements MapleInterface { public void method1() { System.out.println("this is method1"); } public void method2() { System.out.println("this is method2"); } public void method3() { System.out.println("this is method3"); } public static void main(String[] args) { // MapleInterface mapleClass = new MapleClass(); // MapleDecorateAClass mapleDecorateAClass = new MapleDecorateAClass(mapleClass); // mapleDecorateAClass.method1(); // mapleDecorateAClass.method2(); // mapleDecorateAClass.methodA(); // MapleDecorateBClass mapleDecorateBClass = new MapleDecorateBClass(mapleDecorateAClass); // mapleDecorateBClass.method1(); // mapleDecorateBClass.methodB(); MapleInterface mapleClass = new MapleClass(); MapleInterface mapleClassProxy = (MapleInterface) new MapleClassProxy(mapleClass).getProxy(); mapleClassProxy.method1(); mapleClassProxy.method2(); mapleClassProxy.method3(); } } package com.luyo.MapleTest; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by Administrator on 2016/11/15. */ public class MapleClassProxy { private Object target; public MapleClassProxy(Object target) { this.target = target; } InvocationHandler hr = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("this method is invoke"); Object reuslt = method.invoke(target, args); System.out.println(" method over......."); return reuslt; } }; public Object getProxy() { return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), hr); } 输出结果: this method is invoke this is method1 method over....... this method is invoke this is method2 method over....... this method is invoke this is method3 method over.......