Java動態代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
/** * HelloWorld.java */ public interface HelloWorld { public int say(String words); } /** * HelloWorldImplements.java */ public class HelloWorldImplements implements HelloWorld { public int say(String words) { System.out.println("I am saying:"+words); return 1; } } /** * HelloWorldHandler.java */ public class HelloWorldHandler implements InvocationHandler { Object target; public HelloWorldHandler(Object target) { super(); this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); Object result=method.invoke(target,args); System.out.println("after"); return result; } } /** * Main.java */ public class Main { public static void main(String[] args) { HelleWorld helleWorld = new HelloWorldImplements(); HelloWorldHandler helloWorldHandler = new HelloWorldHandler(helleWorld); //HelleWorld proxy =(HelleWorld) Proxy.newProxyInstance(HelleWorld.class.getClassLoader(), HelloWorldImplements.class.getInterfaces(), helloWorldHandler); HelleWorld proxy = (HelleWorld) Proxy.newProxyInstance(helleWorld.getClass().getClassLoader(), new Class[]{HelleWorld.class}, helloWorldHandler); proxy.say("fuck the world"); }
|
JDK動態代理和CGLib動態代理的區別
- jdk動態代理的對象需要實現一個接口,不能對類直接進行代理
- CGLIB可以對類進行代理,基於繼承去生成一個子類,在子類裏對父類的方法進行覆蓋,所以最好不要用final修飾方法
- CGLIB的性能和JDK有所區別