java动态代理

 

 

1.创建被代理对象

2.创建代理对象  

3.都实现接口

通过代理对象调用方法,实际是 多态 接口.方法()

 

 

 

 

 

 

 

package com.pgf.reflectionP;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*动态代理类*
 * d
 * @author pgf
 *
 */
interface Subject{
 void action();
}

class MyJect implements Subject{
 @Override
 public void action() {
  System.out.println("我是一个被代理类-----");
 }
}

class MyInvocationHanlder implements InvocationHandler{
 Object obj;
 //初始化这个被代理对象,返回一个代理对象
 public Object initObj(Object obj){
  this.obj = obj;
  return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
 }
 
 //通过代理类对象调用被代理类中的方法 会转换为这儿调用
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  
  System.out.println("动态代理费用------");
  Object invoke = method.invoke(obj, args);
  return invoke;
 }
 
}

public class TestProxy {
 public static void main(String[] args) {
  MyJect mj = new MyJect();
  MyInvocationHanlder mih = new MyInvocationHanlder();
   Object initObj = mih.initObj(mj);
//   System.out.println(initObj);
   Subject s = (Subject)initObj;
   s.action();
//  
//   //
   NikeFactory  nf = new NikeFactory();
   ClothProduct initObj2 = (ClothProduct)mih.initObj(nf);
   initObj2.productCloth();
  
 }
}

 

 

 

 

 

 

 

 

 

 

 

静态代理

 

package com.pgf.reflectionP;

/**
 * 代理类
 * @author pgf
 *
 */
public class NikeFactoryProxy implements ClothProduct{
 //传入一个接口对象
 ClothProduct cp;
 public NikeFactoryProxy(ClothProduct cp){
  this.cp = cp;
 }

 @Override
 public void productCloth() {
  System.out.println("收取代理费用----");
  cp.productCloth();
 }

 public static void main(String[] args) {
  NikeFactory nf = new NikeFactory();//创建被代理类的对象
  NikeFactoryProxy nfp = new NikeFactoryProxy(nf);//创建代理对象
  nfp.productCloth();
 }
 
}

posted on 2018-04-11 10:46  HelloWorld20180327  阅读(71)  评论(0编辑  收藏  举报

导航