熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Simple-level Dynamic Proxy(1)

2022-06-13   來源: Java高級技術 



package poxy;

import javalangreflectInvocationHandler;
import javalangreflectMethod;
import javalangreflectProxy;

/**
* Simple Dynamic Proxy show a single interface a single instance case
*    
* @author daniel zhou
*/
public class SimpleDynamicProxy {
  /**
    * @param args
    */
  public static void main(String[] args) {
    //generate a hanlder
    ProxyHanlder hanlder=new ProxyHanlder();
    /*
     * register instance to hanlder get the interfaces proxy
     */
    Dog dogProxy=(Dog) hanldergenerateProxyHanlder(new Dog(){
      @Override
      public String eat(String food) {
        return Daniels dog just ate an + food +!;
      }
    });
    //do method by proxy
    String result = dogProxyeat(big bone);
    //take a look
    Systemoutprintln(result);
  }
}

//Proxy Handler    
class ProxyHanlder implements InvocationHandler{
  //container
  Object obj = new Object();
    
  public Object generateProxyHanlder(Object obj) {
    //store it
    thisobj = obj;    
    //return interface proxy
    return ProxynewProxyInstance(objgetClass()getClassLoader()
                     objgetClass()getInterfaces()
                     this);
  }

  @Override
  public Object invoke(Object proxy Method method Object[] args)
      throws Throwable {
    Object result=null;
    result=methodinvoke(obj args);
    return result;
  }
    
}

//interface
interface Dog{    
  String eat(String food);
}

  本文出自 專注JEE系列規范下的開源技術 博客請務必保留此出處


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27626.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.