动态代理案例1:运用Proxy动态代理来增强方法

动态代理案例1:
/*要求:运用Proxy动态代理来增强方法
题目:
    1.定义接口Fruit,其中有addFruit方法
    2.定义实现类FruitImpl,实现Fruit接口
    3.定义测试类,利用动态代理类的方式,增强addFruit方法*/

  1 import java.lang.reflect.Proxy;
  2  import java.lang.reflect.InvocationHandler;
  3  import java.lang.reflect.Method;
  4  import java.lang.reflect.InvocationTargetException;
  5 
  6 //接口
  7 interface Fruit{
  8      public abstract void addFruit();
  9  }
 10 
 11 //实现类
 12 class FruitImpl implements Fruit{
 13      @Override
 14      public void addFruit(){
 15          System.out.println("添加水果...");
 16      }
 17  }
 18 
 19 //测试类---编写代理,增强实现类中的方法
 20 public class FruitDemo{
 21      public static void main(String[] args){
 22          //创建动态代理对象
 23         Object f = Proxy.newProxyInstance(FruitImpl.class.getClassLoader(), FruitImpl.class.getInterfaces(),
 24              new InvocationHandler(){
 25                  @Override
 26                  public Object invoke(Object Proxy, Method method, Object[] args){
 27                      System.out.println("选择水果.....................");
 28                      Object obj = null;
 29                          try{
 30                              obj = method.invoke(new FruitImpl(),args);
 31                          }catch(IllegalAccessException | InvocationTargetException | IllegalArgumentException e){
 32                              e.printStackTrace();
 33                          }
 34                      System.out.println("添加成功~~");
 35                      return obj;
 36                  }
 37              }
 38          );
 39 
 40         //代理对象向下(接口)转型
 41         Fruit f1 = (Fruit) f;
 42 
 43         //转型后的对象执行原方法(已增强)
 44          f1.addFruit();
 45      }
 46  }
 47 
posted @ 2017-07-08 18:19  Guangqin_Hu  阅读(1127)  评论(0编辑  收藏  举报