反射-动态代理(实例)

来源:互联网 发布:什么叫菜鸟网络 编辑:程序博客网 时间:2024/06/02 04:12

//生产车间
public interface ClothingFactory {

void productClothing();

}
——————————————————————————————
//李宁公司
public class LiNing implements ClothingFactory{

@Overridepublic void productClothing() {    System.out.println("生产出李宁服装一批");}

}
——————————————————————————————
//动态代理类
public class DynaProxyHandler implements InvocationHandler {
// 目标对象
private Object target;

public Object newProxyInstance(Object target) {    this.target = target;    return Proxy.newProxyInstance(this.target.getClass().getClassLoader()//类加载器            , this.target.getClass().getInterfaces()//代理要实现的借口列表            , this//调用处理程序            );}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)        throws Throwable {    Object result = null;    try {        result = method.invoke(this.target, args);//通过反射调用目标对象上对应的方法    } catch (Exception e) {        // TODO Auto-generated catch block        throw e;    }    return result;}

}

——————————————————————————————
public class Customer {

public static void main(String[] args) {    DynaProxyHandler handler = new DynaProxyHandler();    ClothingFactory cf=(ClothingFactory) handler.newProxyInstance(new LiNing());    cf.productClothing();}

}

0 0