import java.lang.reflect.*;
import java.util.*;
//切面功能接口
public interface Advice
{
void before(Method method);
void after(Method method);
}
//切面功能的實現類
public class MyAdvice implements Advice
{
public void before(Method method)
{
System.out.println(method.getName()+" 我的前插入");
}
@Override
public void after(Method method)
{
System.out.println(method.getName()+" 我的後插入");
}
}
public class ProxyExam
{
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException
{
//代理目標類
final TreeMap tree = new TreeMap();
//代理功能類
final Advice advice = new MyAdvice();
Map map3 = (Map)getProxy(tree,advice);
map3.put("a", "b");
map3.put("c", "d");
map3.put("e", "f");
System.out.println(map3.size());
}
private static Object getProxy(final Object target,final Advice advice)
{
Object map3 = Proxy.newProxyInstance(
//接口的類加載器
target.getClass().getClassLoader(),
//接口的字節碼文件,這裏可能有多個所以用數組
target.getClass().getInterfaces(),
//InvocationHandler 參數
new InvocationHandler()
{
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable
{
/* System.out.println(method.getName()+" 我的前插入");*/
advice.before(method);
Object reVal=method.invoke(target, args);
/*System.out.println(method.getName()+" 我的後插入");*/
advice.after(method);
return reVal;
}
});
return map3;
}
}
|
Aop小框架
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.