使用CGLIB检测JavaBean被修改字段

使用CGLIB检测JavaBean被修改字段

public class DTODataChangeInterceptor implements MethodInterceptor, Serializable
{
 private static final String SET = "set";
 private Set changedPropSet;
 
 public DTODataChangeInterceptor()
 {
  changedPropSet = new HashSet();
 }

 public Object intercept(Object obj, Method method, Object[] args,
   MethodProxy proxy) throws Throwable
 {
  String name = method.getName();

  if (name.startsWith(SET))
  {
   String s = name.substring(SET.length() - 1);
   String propName = StringUtils.firstLowerCase(s);
   changedPropSet.add(propName);
  }

  return proxy.invokeSuper(obj, args);
 }
 
 public Set getChangedPropSet()
 {
  return Collections.unmodifiableSet(changedPropSet);
 }
 
 public void reset()
 {
  changedPropSet.clear();
 }
}

然后如下调用来初始化javaBean

  Enhancer enhancer = new Enhancer();
  enhancer.setSuperclass(destClass);
  enhancer.setCallback(new DTODataChangeInterceptor());
  
  IValueObject newBean = (IValueObject) enhancer.create();

........初始化newBean

  DTODataChangeInterceptor interceptor = InterceptorUtils
//    .getDTODataChangeInterceptor(newBean);
  interceptor.reset();

然后就可以将newBean传递给其他层进行操作,操作完毕,调用:
 public static DTODataChangeInterceptor getDTODataChangeInterceptor(Object obj)
 {
  if(!(obj instanceof Factory))
  {
   return null;
  }
  Factory f = (Factory)obj;
  Callback[] callBacks = f.getCallbacks();
  for(int i=0,n=callBacks.length;i<n;i++)
  {
   Callback callBack = callBacks[i];
   if(callBack instanceof DTODataChangeInterceptor)
   {
    return (DTODataChangeInterceptor)callBack;
   }
  }
  return null;
 }
既可以得到哪些字段变化了。

 

你可能感兴趣的:(使用CGLIB检测JavaBean被修改字段)