dingfirst

On the Road

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  8 随笔 :: 2 文章 :: 3 评论 :: 0 Trackbacks

先看一下Proxy的两种用法:

public   interface  Foo  {
    
int  doSomthing();
}
   一个基本的实现:
public class FooImpl implements Foo {
    
public FooImpl() {
    }


    
public int doSomthing() {
        System.out.println(
"FooImpl doSomthing");
        
return 10;
    }

    
}
   调用处理类,这也是aop的一种实现方式,呵呵。
public class MyInvocationHandler implements InvocationHandler{
    Object proxyObject;
    
    
public MyInvocationHandler(Object _proxyObject) {
        
this.proxyObject=_proxyObject;
    }


    
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(
"in proxy instance");
        
return method.invoke(proxyObject,args);
    }

}
   两种实现方式:
public class ProxyUse {
    
public ProxyUse() {
    }


    
public void useProxy1() throws SecurityException, NoSuchMethodException, InvocationTargetException,
            IllegalArgumentException, IllegalAccessException, InstantiationException 
{
        FooImpl obj 
= new FooImpl();
        InvocationHandler handler 
= new MyInvocationHandler(obj);
        Class proxyClass 
= Proxy.getProxyClass(
                Foo.
class.getClassLoader(), new Class[] {Foo.class});
        Foo f 
= (Foo) proxyClass.
                getConstructor(
new Class[] {InvocationHandler.class}).
                newInstance(
new Object[] {handler});
        System.out.println(f.doSomthing());
    }

    
    
public void useProxy2() throws SecurityException, NoSuchMethodException, InvocationTargetException,
            IllegalArgumentException, IllegalAccessException, InstantiationException 
{
        FooImpl obj 
= new FooImpl();
        InvocationHandler handler 
= new MyInvocationHandler(obj);
        Foo f 
= (Foo) Proxy.newProxyInstance(
            Foo.
class.getClassLoader(),
            
new Class[] { Foo.class },
            handler
            );
        System.out.println(f.doSomthing());
    }

    
    
public static void main(String [] args){
        ProxyUse use
=new ProxyUse();
        
try{
            use.useProxy1();
            use.useProxy2();
        }
catch(Exception ex){
            ex.printStackTrace();
        }

    }


}

看一下java api doc

static InvocationHandlergetInvocationHandler(Object proxy)
          返回指定代理实例的调用处理程序。
static Class<?>getProxyClass(ClassLoader loader, Class<?>... interfaces)
          返回代理类的 java.lang.Class 对象,并向其提供类加载器和接口数组。
static booleanisProxyClass(Class<?> cl)
          当且仅当指定的类通过 getProxyClass 方法或 newProxyInstance 方法动态生成为代理类时,返回 true。
static ObjectnewProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
          返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。

没时间了,先这样吧。


 

posted on 2006-07-26 17:48 dingfirst 阅读(255) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: