使用Proxy的newProxyInstance方法创建动态代理。

  1. public static Object newProxyInstance(ClassLoader loader,
  2. Class<?>[] interfaces,
  3. InvocationHandler h)
  4. loader:自然是类加载器
  5. interfaces:需要代理的接口
  6. hInvocationHandler对象
  1. public interface InvocationHandler{
  2. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
  3. }
  4. proxy :代理对象
  5. method:代理对象调用的方法
  6. args:调用的方法中的参数

例子

  1. package com.cimon.simplerpc.prework;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. /**
  6. * @author chenrenbing
  7. * @date 2021/06/20
  8. * 动态代理模式
  9. * */
  10. public class DynamicProxyDemo {
  11. public static void main(String args[]){
  12. WineService wineService1 = new WineServiceImpl1();
  13. WineService wineService2 = new WineServiceImpl2();
  14. InvocationHandler handler1 = new WineHandler(wineService1);
  15. InvocationHandler handler2 = new WineHandler(wineService2);
  16. WineService proxy1 = (WineService) Proxy.newProxyInstance(WineService.class.getClassLoader(),wineService1.getClass().getInterfaces(),handler1);
  17. proxy1.sellWine();
  18. proxy1.amount(1499);
  19. WineService proxy2 = (WineService) Proxy.newProxyInstance(WineService.class.getClassLoader(),wineService1.getClass().getInterfaces(),handler2);
  20. proxy2.sellWine();
  21. proxy2.amount(999);
  22. }
  23. }
  24. interface WineService{
  25. void sellWine();
  26. int amount(int a);
  27. }
  28. class WineServiceImpl1 implements WineService{
  29. public void sellWine(){
  30. System.out.println(" 茅台... ");
  31. }
  32. public int amount(int a){
  33. System.out.println(" 茅台价格 : "+ a+"元");
  34. return a;
  35. }
  36. }
  37. class WineServiceImpl2 implements WineService{
  38. public void sellWine(){
  39. System.out.println(" 五粮液... ");
  40. }
  41. public int amount(int a){
  42. System.out.println(" 五粮液 : "+ a+"元");
  43. return a;
  44. }
  45. }
  46. class WineHandler implements InvocationHandler{
  47. private Object wine;
  48. public WineHandler(Object wine){
  49. this.wine = wine;
  50. }
  51. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
  52. System.out.println(" 卖酒了..." + this.wine.getClass().getSimpleName());
  53. Object result = method.invoke(wine,args);
  54. System.out.println(" 卖完了....");
  55. return result;
  56. }
  57. }
  58. 运行结果:
  59. 卖酒了...WineServiceImpl1
  60. 茅台...
  61. 卖完了....
  62. 卖酒了...WineServiceImpl1
  63. 茅台价格 : 1499
  64. 卖完了....
  65. 卖酒了...WineServiceImpl2
  66. 五粮液...
  67. 卖完了....
  68. 卖酒了...WineServiceImpl2
  69. 五粮液 : 999
  70. 卖完了....

参考
1、java中的代理模式