動態代理案例1:運用Proxy動態代理來增強方法,案例proxy

來源:互聯網
上載者:User

動態代理案例1:運用Proxy動態代理來增強方法,案例proxy

動態代理案例1:
/*要求:運用Proxy動態代理來增強方法
題目:
    1.定義介面Fruit,其中有addFruit方法
    2.定義實作類別FruitImpl,實現Fruit介面
    3.定義測試類別,利用動態代理類的方式,增強addFruit方法*/

  1 import java.lang.reflect.Proxy;  2  import java.lang.reflect.InvocationHandler;  3  import java.lang.reflect.Method;  4  import java.lang.reflect.InvocationTargetException;  5   6 //介面  7 interface Fruit{  8      public abstract void addFruit();  9  } 10  11 //實作類別 12 class FruitImpl implements Fruit{ 13      @Override 14      public void addFruit(){ 15          System.out.println("添加水果..."); 16      } 17  } 18  19 //測試類別---編寫代理,增強實作類別中的方法 20 public class FruitDemo{ 21      public static void main(String[] args){ 22          //建立動態代理對象 23         Object f = Proxy.newProxyInstance(FruitImpl.class.getClassLoader(), FruitImpl.class.getInterfaces(), 24              new InvocationHandler(){ 25                  @Override 26                  public Object invoke(Object Proxy, Method method, Object[] args){ 27                      System.out.println("選擇水果....................."); 28                      Object obj = null; 29                          try{ 30                              obj = method.invoke(new FruitImpl(),args); 31                          }catch(IllegalAccessException | InvocationTargetException | IllegalArgumentException e){ 32                              e.printStackTrace(); 33                          } 34                      System.out.println("添加成功~~"); 35                      return obj; 36                  } 37              } 38          ); 39  40         //代理對象向下(介面)轉型 41         Fruit f1 = (Fruit) f; 42  43         //轉型後的對象執行原方法(已增強) 44          f1.addFruit(); 45      } 46  } 47 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.