java動態代理簡單一實例

來源:互聯網
上載者:User

在目前的Java開發包中包含了對動態代理的支援,但是其實現只支援對介面的的實現。

其實現主要通過是java.lang.reflect.Proxy類和java.lang.reflect.InvocationHandler介面。

Proxy類主要用來擷取動態代理對象,InvocationHandler介面用來限制式呼叫者實現,如下,HelloWorld介面定義的業務方法,HelloWorldImpl是HelloWorld介面的實現,HelloWorldHandler是InvocationHandler介面實現。代碼如下:

業務介面:

public interface HelloWorld {
void sayHelloWorld();

}

業務介面實現:
public class HelloWorldImpl implements HelloWorld {

@Override
public void sayHelloWorld() {
  System.out.println("Hello World");
 
}

}

InvocationHandler實現,需要在介面方法調用前後加入一部份處理工作,這裡僅僅在方法調用前後向後台輸出兩句字串,其代碼如下:

import java.lang.reflect.*;

public class HelloWorldHandler implements  InvocationHandler {
private Object objOriginal;

  public HelloWorldHandler(Object obj) {

         this.objOriginal = obj ;

  }

@Override
public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
   Object result ;
   doBefore();
   result = method.invoke(this.objOriginal, args);
   doAfter();

  return result;
}

   private void doBefore() {

          System.out.println("before method invoke!");
   }

  

   private void doAfter() {
          System.out.println("after method invoke!");

   }
}

測試代碼:

import java.lang.reflect.*;

public class Test {

/**
  * @param args
  */
public static void main(String[] args) {
  // TODO Auto-generated method stub
  HelloWorld hw=new HelloWorldImpl();
  InvocationHandler handler=new HelloWorldHandler(hw);
  HelloWorld proxy=(HelloWorld)Proxy.newProxyInstance(hw.getClass().getClassLoader(), hw.getClass().getInterfaces(), handler);
  proxy.sayHelloWorld();

}

}

運行結果:

before method invoke!
Hello World
after method invoke!

聯繫我們

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