您的位置:首页 > 其它

InvocationHandler+工厂设计模式 实现动态代理

2014-01-16 11:33 453 查看
工厂类

package proxy;

import java.lang.reflect.Proxy;

/**

 * 接口工厂

 * @author lizh

 * @date  2014-1-16上午11:31:34

 * @fileName Factory.java

 * @package proxy

 * @project Test

 */

public class Factory {

 public static <T> T instance(Class<T> c){

  if(c.isInterface()){

   InterfaceAnno anno = c.getAnnotation(InterfaceAnno.class);

   if(anno == null){

    System.out.println("接口未使用InterfaceAnno标签");

   }else{

    String implClass = anno.implClass();

    try {

     Class<?> cl = Class.forName(implClass);

     return (T) Proxy.newProxyInstance(c.getClassLoader(),new Class[]{c}, new MyInvocationHandler(cl));

    } catch (ClassNotFoundException e) {

     e.printStackTrace();

    }

   }

  }else{

   return (T) Proxy.newProxyInstance(c.getClassLoader(),c.getInterfaces(), new MyInvocationHandler(c));

  }

  return null;

 }

}

 

接口实现类标签

package proxy;

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

public @interface InterfaceAnno {

 String implClass();

}

handle

package proxy;

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

/**

 * handler类

 * @author lizh

 * @date  2014-1-16上午11:30:55

 * @fileName MyInvocationHandler.java

 * @package proxy

 * @project Test

 */

public class MyInvocationHandler implements InvocationHandler{

 private Class<?> service =null;

 

 public MyInvocationHandler() {

 }

 public MyInvocationHandler(Class<?> service){

  this.service = service;

 }

 @Override

 public Object invoke(Object proxy, Method method, Object[] args)

   throws Throwable {

  System.out.print(method.getName()+"准备执行");

  Object a = method.invoke(service.newInstance(), args);

  return a;

 }

 public Class<?> getService() {

  return service;

 }

 public void setService(Class<?> service) {

  this.service = service;

 }

 

}

测试接口

package proxy;

@InterfaceAnno(implClass="proxy.ShoppingImpl")

public interface Shopping {

 void doSomeThing();

 void pay();

}

测试实现类

package proxy;

public class ShoppingImpl implements Shopping{

 @Override

 public void doSomeThing() {

  System.out.println("doSomeThing");

 }

 @Override

 public void pay() {

  System.out.println("pay");

 }

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: