為了鞏固 CGLib 的知識
例
(
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
}
public String getName()
{
return name;
}
public void setName(String name)
{
this
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this
}
}
(
import java
import java
import java
import java
import net
import net
public class JavaBeanDataChangeInterceptor implements MethodInterceptor
{
private static final String SET =
private Set changedPropSet;
public JavaBeanDataChangeInterceptor()
{
changedPropSet = new HashSet();
}
public Object intercept(Object obj
MethodProxy proxy) throws Throwable
{
String name = method
if (name
{
String s = name
changedPropSet
}
return proxy
}
public Set getChangedPropSet()
{
return Collections
}
public void reset()
{
changedPropSet
}
}
定義一個集合 changedPropSet 用來存放修改了的字段名
在 intercept 方法中
(
import net
import net
public class JavaBeanInterceptorUtils
{
public static JavaBeanDataChangeInterceptor getInterceptor(
Object obj)
{
if (!(obj instanceof Factory))
{
return null;
}
Factory f = (Factory) obj;
Callback[] callBacks = f
for (int i =
{
Callback callBack = callBacks[i];
if (callBack instanceof JavaBeanDataChangeInterceptor)
{
return (JavaBeanDataChangeInterceptor) callBack;
}
}
return null;
}
}
這個 JavaBeanInterceptorUtils 只有一個方法 getInterceptor
前邊提到了
(
public class MainApp
{
public static void main(String[] args)
{
Enhancer enhancer = new Enhancer();
enhancer
enhancer
PersonInfo info = (PersonInfo) enhancer
// 對生成的 JavaBean 做一些初始化
info
info
info
// 得到攔截器
JavaBeanDataChangeInterceptor interceptor = JavaBeanInterceptorUtils
// 復位修改字段記錄集合
interceptor
// 對 JavaBean 做一些修改
editPersonInf(info);
// 得到修改了的字段
Iterator it = interceptor
while (it
{
System
}
}
private static void editPersonInf(PersonInfo info)
{
info
info
}
}
運行結果
Address
Name
這個
很多資料中都說如果要使用 JDK Proxy
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26735.html