動態代理類的創建實例

定義一個接口:<p>package com.proxy;</p><p>public interface Person {
 String eat(String name);
 String play(String where);</p><p>}</p>
定義一個類,該類作爲目標類,實現Person接口<p>package com.proxy;</p><p>public class Student implements Person {</p><p> @Override
 public String eat(String name) {
  // TODO Auto-generated method stub
  String eat="今天喫"+name+",非常好喫";
  return eat;
 }</p><p> @Override
 public String play(String where) {
  // TODO Auto-generated method stub
  String we="今晚去"+where+"幽會";
  return we;
 }</p><p>}</p>
另定義一個接口,用於添加其他功能,如系統,日誌,事物等<p>package com.proxy;</p><p>import java.lang.reflect.Method;</p><p>public interface Adive {
 void before(Method method);
 void after(Method method);</p><p>}</p>
再定義一個類,實現Adive接口,作爲日後維護代理類的建議類<p>package com.proxy;</p><p>import java.lang.reflect.Method;</p><p>public class MySystem implements Adive{
 private long startTime;
 @Override
 public void before(Method method) {
  // TODO Auto-generated method stub
  startTime=System.currentTimeMillis(); 
  System.out.println("在目標類前添加系統功能");
 }</p><p> @Override
 public void after(Method method) {
  // TODO Auto-generated method stub
  long endTime=System.currentTimeMillis();
  System.out.println("在目標類後添加系統功能");
  
  System.out.println(endTime-startTime);
  
 }</p><p>}</p>
最後定義代理類,代碼如下<p>package com.proxy;</p><p>import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;</p><p>public class ProxyTest {
 public static void main(String[] args) throws Exception{
  
  Person person=(Person)getProxy(new Student(),new MySystem());
  System.out.println(person.eat("魚"));;
  System.out.println(person.play("南寧"));;
 }</p><p>/*</p><p>此函數以目標類和需日後添加的事物類作爲參數,實現獲取動態代理的方法</p><p>*/</p><p> private static Object getProxy(final Object target,final Adive adive) {
  Object proxy=Proxy.newProxyInstance(
    target.getClass().getClassLoader(),  //這裏接收的是目標類的接口類的類加載器
    target.getClass().getInterfaces()       //這裏接收的是接口
    , 
    new InvocationHandler() {           //這裏接收的是InvocationHandler接口的實現類對象
         
     @Override
     public Object invoke(Object proxy, Method method, Object[] args)
       throws Throwable {
      // TODO Auto-generated method stub
      adive.before(method);
      Object obj = method.invoke(target, args);
      System.out.println("黃河之水天上來");
      adive.after(method);
      return obj;
     }
    }
    );
  return proxy;
 }</p><p>}</p>

運行結果如下:


在目標類前添加系統功能
黃河之水天上來
在目標類後添加系統功能
0
今天喫魚,非常好喫
在目標類前添加系統功能
黃河之水天上來
在目標類後添加系統功能
0
今晚去南寧幽會 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章