java动态代理

(1)getProxyClass()静态方法负责创建动态代理类,它的完整定义如下:

public static Class<?> getProxyClass(ClassLoader loader,Class<?>[] interfaces)

参数loader指定动态代理类的类加载器,参数Interfaces指定动态代理类需要实现的所有接口。

(2)newProxyInstance()静态方法负责创建动态代理类的实例,它的完整定义如下:

public static Object newProxyInstance(Class loader,Class<?>[] interfaces,InvocationHandler handler)throws IIlegalArgumentException

 参数loader制定动态代理类的类加载器,参数Interface指定动态搭理类需要实现的所有接口,参数handler指定于动态类关联的InvocationHandler对象。

以下两种方式都创建Foo接口的动态代理类的实例:

/**方式一**/

//创建InvocationHandler对象 

InvocationHandler handler = new MyInvocationHandler(...);

//创建动态代理类

Class proxyClass  = Proxy.getProxyClass(Foo.class.getClassLoader(),new Class[]{Foo.class});

//创建动态代理类的实例

Foo foo = (Foo)proxyClass.getConstructor(new Class[]{InvocationHander.class}).newInstance(new Object[]{ hander}); 

 

/**方式二**/

 //创建InvocationHandler对象

InvocationHandler handler = new MyInvocationHandler(...);

//直接创建动态代理类的实例

Foo foo = (Foo)Proxy.newProxyInstance(Foo.class.getClassLoader(),new Class[]{Foo.class},handler);

 

 

 //HelloServiceProxyFactory.java

package proxy;
import java.lang.reflect.*;
public class HelloServiceProxyFactory {
  public static HelloService getHelloServiceProxy(final HelloService helloService){
    InvocationHandler handler=new InvocationHandler(){
      public Object invoke(Object proxy,Method method,Object args[])throws Exception{
        System.out.println("before calling "+method);
        Object result=method.invoke(helloService,args);
        System.out.println("after calling "+method);
        return result;
      }
  };
    Class classType=HelloService.class;
    return (HelloService)Proxy.newProxyInstance(classType.getClassLoader(),
                                          new Class[]{classType},
                                          handler);
  }
}

 

//Client2.java 

package proxy;
public class Client2{
  public static void main(String args[]){
    HelloService helloService=new HelloServiceImpl();
    HelloService helloServiceProxy=
               HelloServiceProxyFactory.getHelloServiceProxy(helloService);
    System.out.println("动态代理类的名字为"
                       +helloServiceProxy.getClass().getName());
    System.out.println(helloServiceProxy.echo("Hello"));
  }
}

 

posted @ 2018-11-30 21:42  lomt5  阅读(64)  评论(0)    收藏  举报