java 之 動態代理

來源:互聯網
上載者:User

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 }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.