java 之 動態代理
AOP,《thinking in java 4th》中沒有過多闡述,只能結合視頻和查找其他資料了。
AOP的大概原理是這樣的:

設計模式高深了,咱連皮毛都觸不到,目前知道這個就行了。
下面是談不上設計模式的建議代碼實踐:
1 import java.lang.reflect.InvocationHandler;
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4
5 public class Test {
6
7 //接口,攢電腦
8 public interface DIY{
9 //去中關村買配件
10 public void buySomthin();
11
12 }
13
14 //我要去中關村攢電腦
15 public class DIYPC implements DIY{
16 public DIYPC(){
17 System.out.println("天氣不錯,攢電腦去");
18 }
19
20 @Override
21 public void buySomthin() {
22 // TODO Auto-generated method stub
23 System.out.println("買配件");
24
25 }
26
27 }
28
29 //實現攢電腦的奸商代理
30 public class DIYHandler implements InvocationHandler{
31
32 private Object objProxy;
33
34 public DIYHandler(Object obj){
35 this.objProxy=obj;
36 }
37
38 @Override
39 public Object invoke(Object proxy, Method method, Object[] args)
40 throws Throwable {
41 // TODO Auto-generated method stub
42 System.out.println(" "+objProxy.getClass().getSimpleName()+"-"+method.getName());
43
44
45 return method.invoke(objProxy, args);
46 }
47
48 }
49
50 public static void JianShang(DIY diyProxy){
51 System.out.println("尼瑪奸商的都是返修貨");
52
53 //Proxy.newProxyInstance會動態實現目標的接口,并調用代理的invoke方法,
54 //然后通過類加載器,動態的調用這個新生成的class并返回
55 diyProxy.buySomthin();
56 System.out.println("js笑了,我內牛滿面了");
57 }
58
59 public static void main(String[] args){
60 Test t=new Test();
61 DIY diy=t.new DIYPC();
62 DIY diyProxy=(DIY)Proxy.newProxyInstance(diy.getClass().getClassLoader(), diy.getClass().getInterfaces(), t.new DIYHandler(diy));
63 JianShang(diyProxy);
64
65 }
66
67
68 }
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4
5 public class Test {
6
7 //接口,攢電腦
8 public interface DIY{
9 //去中關村買配件
10 public void buySomthin();
11
12 }
13
14 //我要去中關村攢電腦
15 public class DIYPC implements DIY{
16 public DIYPC(){
17 System.out.println("天氣不錯,攢電腦去");
18 }
19
20 @Override
21 public void buySomthin() {
22 // TODO Auto-generated method stub
23 System.out.println("買配件");
24
25 }
26
27 }
28
29 //實現攢電腦的奸商代理
30 public class DIYHandler implements InvocationHandler{
31
32 private Object objProxy;
33
34 public DIYHandler(Object obj){
35 this.objProxy=obj;
36 }
37
38 @Override
39 public Object invoke(Object proxy, Method method, Object[] args)
40 throws Throwable {
41 // TODO Auto-generated method stub
42 System.out.println(" "+objProxy.getClass().getSimpleName()+"-"+method.getName());
43
44
45 return method.invoke(objProxy, args);
46 }
47
48 }
49
50 public static void JianShang(DIY diyProxy){
51 System.out.println("尼瑪奸商的都是返修貨");
52
53 //Proxy.newProxyInstance會動態實現目標的接口,并調用代理的invoke方法,
54 //然后通過類加載器,動態的調用這個新生成的class并返回
55 diyProxy.buySomthin();
56 System.out.println("js笑了,我內牛滿面了");
57 }
58
59 public static void main(String[] args){
60 Test t=new Test();
61 DIY diy=t.new DIYPC();
62 DIY diyProxy=(DIY)Proxy.newProxyInstance(diy.getClass().getClassLoader(), diy.getClass().getInterfaces(), t.new DIYHandler(diy));
63 JianShang(diyProxy);
64
65 }
66
67
68 }
浙公網安備 33010602011771號