p { margin-bottom: 0.21cm; }
有了此方法和此接口后 我们使用的时候只需要实现Advice 接口 Advice 接口为通知接口根据需要重写接口里面的方法 调用代理类时 传入我们实现的接口类就行了
通用方法
建议类接口
public interface Advice {
void beforMethod(Method method);
void afterMethod(Method method);
}
代理方法
private static Object getProxy( final Object target , final Advice advice) {
Object proxy3 = Proxy. newProxyInstance (
target .getClass().getClassLoader()
, target .getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// 前置通告
advice.afterMethod(method);
// 执行对象的方法 使用的反射技术
Object reVal = method.invoke( target , args);
// 执行方法
advice.beforMethod(method);
return reVal;
}
});
return proxy3;
}
代理使用实例
实现接口
public class MyAdvice implements Advice {
long beginTime =0;
@Override
public void afterMethod(Method method) {
// TODO Auto-generated method stub
System. out .println( " 结束 -- 之后通告 " );
long endTime = System. currentTimeMillis ();
System. out .println(method.getName()+ " runing time Object" + ( beginTime - System. currentTimeMillis ()));
}
@Override
public void beforMethod(Method method) {
// TODO Auto-generated method stub
System. out .println( " 开始 -- 之前通告 " );
beginTime = System. currentTimeMillis ();
}
}
是哟调用代理类
Collection proxy3 = (Collection) getProxy (target, new MyAdvice());
proxy3.add( "zxx" );