CGLib如何实现变化字段探测的功能
为了巩固 cglib 的知识,下面我们实现一个稍微复杂一点的例子。
例、请实现一个拦截器,使其能够检测一个 javabean 的哪些字段改变了。
( 1 )首先定义一个 javabean 。
public class personinfo
{
private string name;
private string email;
private int age;
private string address;
public string getemail()
{
return email;
}
public void setemail(string email)
{
this.email = email;
}
public string getname()
{
return name;
}
public void setname(string name)
{
this.name = name;
}
public string getaddress()
{
return address;
}
public void setaddress(string address)
{
this.address = address;
}
public int getage()
{
return age;
}
public void setage(int age)
{
this.age = age;
}
}
( 2 )定义一个 methodinterceptor ,这一步是最关键的 。
import java.lang.reflect.method;
import java.util.collections;
import java.util.hashset;
import java.util.set;
import net.sf.cglib.proxy.methodinterceptor;
import net.sf.cglib.proxy.methodproxy;
public class javabeandatachangeinterceptor implements methodinterceptor
{
private static final string set = "set";
private set changedpropset;
public javabeandatachangeinterceptor()
{
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());
changedpropset.add(s);
}
return proxy.invokesuper(obj, args);
}
public set getchangedpropset()
{
return collections.unmodifiableset(changedpropset);
}
public void reset()
{
changedpropset.clear();
}
}
定义一个集合 changedpropset 用来存放修改了的字段名,增加了一个方法 reset 用来清空此集合,增加了一个 getchangedpropset 方法用来供外界得到修改了的字段,为了防止调用者对 changedpropset 做修改,因此我们采用 collections.unmodifiableset 对返回的集合进行不可修改的修饰。
在 intercept 方法中,我们判断如果被调用的方法以 set 开头,则把此字段名放入 changedpropset 集合中。
( 3 )定义剖析用工具类。
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
public class JavaBeanInterceptorUtils
{
public static JavaBeanDataChangeInterceptor getInterceptor(
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 JavaBeanDataChangeInterceptor)
{
return (JavaBeanDataChangeInterceptor) callBack;
}
}
return null;
}
}
这个 JavaBeanInterceptorUtils 只有一个方法 getInterceptor ,这个方法用于从一个被 CGLib 代理的 JavaBean 中取出拦截器 JavaBeanDataChangeInterceptor 。
前边提到了, CGLib 实现拦截的方式就是生成被拦截类的子类,这个子类实现了 net.sf.cglib.proxy.Factory 接口,这个接口中有一个非常重要的方法 getCallbacks() ,通过这个方法我们可以得到所有的拦截器 。
Tag: cglib
文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。