1、java自帶的proxy類可以創建動態類,如果一個類實現了一個接口那么久可以為這個類創建代理。
2、代理:就是當用戶要調用一個類的方法時,用戶可以通過調用代理,代理通過接口調用原來的類的方法,代理在把方法給用戶前可以添加一些方法,如錯誤日志,用戶類的方法運行的時間來監聽類方法的性能。當代理完成時候就是當代理調用方法時候,就會啟動InvocationHandler里的invoke方法。用戶並不知道用戶要為哪個類帶理,因此在框架中用配置文件來獲取代理的類,用戶需要用框架時候就修改配置文件即可。
public class Proxydemo {
public static void main(String[] args) throws Exception {
//這是分2部,來實現collection的代理的,下面是1步實現代理,並且是任何類
// Class classproxy=Proxy.getProxyClass(Collection.class.getClassLoader(),Collection.class);
// Constructor[]constructors=classproxy.getConstructors();
// Constructor constructor=classproxy.getConstructor(java.lang.reflect.InvocationHandler.class);
// for(Constructor c:constructors)
// {
// System.out.println(c.toString());
// }
//// final ArrayList a=new ArrayList<>();
// Collection c=(Collection) constructors[0].newInstance(new InvocationHandler(){
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args)
// throws Throwable {
// ArrayList a=new ArrayList<>();
// System.out.println(System.currentTimeMillis());
// Object ob=method.invoke(a ,args);
// System.out.println("a的size:"+a.size());
// System.out.println(System.currentTimeMillis());
// return ob;
// }
//
// });
//// c.add("dada"); c.add("dada");
//// System.out.println( c.size());
//
//下面是實現代理的原理,pr是給代理的接口,advice是代理要監控方法的接口
final Pro pr=new ProtexTest();
final Advice advice=new MyAdvice();
Pro classproxy=(Pro)Proxy.newProxyInstance(pr.getClass().getClassLoader(), new Class[]{Pro.class}, new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforemethod();//這是方法前調用的方法
Object o=method.invoke(pr, args);
advice.aftermethod();//這是方法后調用的方法
return o;
}
});
//當調用sayhello時候,系統就去找代理調用InvocationHandler里的invoke方法。
classproxy.sayhello();
/* 所以打印結果為:
1441522392491
hello
1441522392493
*/
//調用代理函數
Pro o=(Pro) daili(pr,advice);
o.sayhello();
}
/******************下面可以吧上面的方法抽出為一個代理方法,為任何實現接口的類代理*****/
/*
* target 為目標類實現的接口
* advice為代理要監控方法的接口
*/
public static Object daili(final Object target,final Advice advice)
{
Object classproxy=(Object)Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforemethod();//這是方法前調用的方法
Object o=method.invoke(target, args);
advice.aftermethod();//這是方法后調用的方法
return o;//返回方法執行后返回的值
}
});
return classproxy;
}
}
