举例:
- jdk自带动态代理
- javaassit字节码操作库实现
- CGLIB
- ASM底层操作
实际例子:
使用jdk自带动态代理
- java.lang.reflect.Proxy 作用
- 动态生成代理类和对象
- java.lang.reflectInvocationHander
- 可以通过invoke方法实现对真实角色的代理访问
- 每次通过Proxy生成代理类对象对象时都要指定对应的处理器对象
package com.littlepage.DynamicProxyParttern; public interface Star { //面谈 void confer(); //签合同 void signContract(); //订票 void bookTicket(); //唱歌 void sing(); //收钱 void collectMoney(); }
package com.littlepage.DynamicProxyParttern; public class RealStar implements Star{ @Override public void confer() { System.out.println("Real Star Confer"); } @Override public void signContract() { System.out.println("Real Star SignContract"); } @Override public void bookTicket() { System.out.println("Real Star BookTicket"); } @Override public void sing() { System.out.println("Real Star Sing"); } @Override public void collectMoney() { System.out.println("Real Star CollectMoney"); } }
package com.littlepage.DynamicProxyParttern; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class StarHandler implements InvocationHandler{ Star realStar; public StarHandler(Star realStar) { this.realStar = realStar; } @Override public Object invoke(Object proxy, Method method, Object[] args)//涉及反射 throws Throwable { Object object=null; System.out.println("真正的方法执行"); System.out.println("面谈,签合同,付款,订机票"); if(method.getName().equals("sing")){ method.invoke(realStar, args);//激活调用的方法 } System.out.println("收尾款"); return object; } }
package com.littlepage.DynamicProxyParttern; import java.lang.reflect.Proxy; public class Client { public static void main(String[] args) { RealStar rs=new RealStar(); StarHandler sh=new StarHandler(rs); Star proxy=(Star) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Star.class}, sh); proxy.sing(); } }
运行结果: