CGLib如何实现变化字段探测的功能(2)

分类: J2EE   出处:iocblog整理  更新时间:2009-03-18   添加到收藏  

( 4 ) 主程序

public class MainApp

{

     public static void main(String[] args)

     {

         Enhancer enhancer = new Enhancer();

         enhancer.setSuperclass(PersonInfo.class);

         enhancer.setCallback(new JavaBeanDataChangeInterceptor());

 

         PersonInfo info = (PersonInfo) enhancer.create();[iocblog.net 来源]

         // 对生成的 JavaBean 做一些初始化

         info.setAddress(" 地址 1");

         info.setAge(21);

         info.setName("tom");

 

         // 得到拦截器

         JavaBeanDataChangeInterceptor interceptor = JavaBeanInterceptorUtils

                   .getInterceptor(info);

         // 复位修改字段记录集合

         interceptor.reset();

 

         // 对 JavaBean 做一些修改

         editPersonInf(info);

 

         // 得到修改了的字段

         Iterator it = interceptor.getChangedPropSet().iterator();

         while (it.hasNext())

         {

              System.out.println(it.next());

         }

     }

 

     private static void editPersonInf(PersonInfo info)

     {

         info.setName("Jim");

         info.setAddress("N.Y Street");

     }

}  

运行结果:

Address

Name

 

  这个“变化字段拦截器”是有一定实际意义的,比如可以用来实现“只保存修改了的字段以提高效率”等功能 。

 

  很多资料中都说如果要使用 JDK Proxy ,被代理的对象的类必须要实现接口,这种说法是不严谨的。从上边的例子我们可以看出,正确的说法应该是:如果要使用 JDK Proxy ,那么我们要通过代理调用的方法必须定义在一个接口中。“面向接口编程而不是面向实现编程”是 OOP 开发中的一条基本原则,因此这种限制并不会对我们的开发造成障碍。

上一页 [1] [2]


Tag: cglib



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。