1.实现类
public class CustomInvocationHandle implements InvocationHandler {
private Object target;//目标类
public CustomInvocationHandle(Object o){
this.target=o;
}
//生成代理对象的方法
public Object createProxy(){
//jdk提供了Proxy类 有一个方法专门用来生成代理类对象
Object proxy= Proxy.newProxyInstance(CustomInvocationHandle.class.getClassLoader(),target.getClass().getInterfaces(),this);
return proxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//前置增强 解析表达式,
if (method.getName().indexOf("say")>=0){
showTime();
}
Object returnValue=method.invoke(target,args);
return returnValue;
}
private void showTime() {
System.out.println("时间:"+new Date());
}
}
2.测试前置增强(代理对象调方法前置增强,输出时间)
//System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
//配置将代理类的字节码保存到本地
Hello target=new HelloImpl();//目标类
CustomInvocationHandle handle=new CustomInvocationHandle(target);
Object proxy = handle.createProxy();
System.out.println(proxy);
Hello hi=(Hello)proxy;
hi.sayHello();
hi.sayBye();