java实现动态代理 有jdk 或者cglib,使用jdk的必须实现接口
代理模式实现一
public interface Log{
public void beforelog();
public void aftelog();
}
public class LogImpl implements Log{
@Override
public void beforelog() {
System.out.println("befor");
}
@Override
public void afterlog() {
System.out.println("after");
}
}
public class LogProxy implements Log {
public Log delegate;
public LogProxy (Log delegate){
this.delegate = delegate;
}
@Override
public void beforelog() {
System.out.println("begin ");
delegate.beforelog();
System.out.println("end ");
}
@Override
public void afeterlog() {
System.out.println("begin ");
delegate.afterlog();
System.out.println("end ");
}
}
public class TestProxy {
/**
* @param args
*/
public static void main(String[] args) {
Log log= new LogProxy(new LogImpl());
log.beforelog();
log.afterlog();
}
}
二 jdk 动态代理
public class ProxyFactory implements InvocationHandler {
private Object delegate;
public Object bind(Object delegate){
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
result = method.invoke(delegate, args);
return result;
}
}
public class TestJDKProxy {
public static void main(String[] args) {
Log log= (Log) new ProxyFactory().bind(new LogImpl());
log.beforlog();
log.afterlog();
}
}
三 cglib 代理
public class CglibProxyFactory implements MethodInterceptor {
private Object delegate;
public Object bind(Object delegate){
this.delegate = delegate;
Enhancer hancer = new Enhancer();
hancer.setSuperclass(delegate.getClass());
hancer.setCallback(this);
return hancer.create();
}
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
Object o = arg3.invoke(this.delegate, arg2);
return o;
}
}
public class TestCglibProxy {
public static void main(String[] args) {
DefaulLog log= (DefaulLog) new CglibProxyFactory().bind(new DefaulOffer());
log.beforlog();
log.afterlog();
}
}