欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

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

发布时间:2025/3/14 编程问答 32 豆豆
生活随笔 收集整理的这篇文章主要介绍了 动态代理案例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

转载于:https://www.cnblogs.com/huguangqin/p/7137551.html

总结

以上是生活随笔为你收集整理的动态代理案例1:运用Proxy动态代理来增强方法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。