静态代理
public interface Hello{
void say(String name);
}
public class HelloImpl implements Hello{
@Override
public void say(String name){
System.out.println("Hello! "+name);
}
}
public class HelloProxy implements Hello{
private Hello hello;
public HelloProxy(){
hello = new HelloImpl()
}
@Override
public void say(String name){
before();
hello.say(name);
after();
}
private void before(){
System.out.println("Before");
}
private void after(){
System.out.println("after");
}
}
动态代理
public class DynamicProxy implements InvocationHandler{
private Object target;
public DynamicProxy(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{
before();
Object result = method.invoke(target,args);
after();
return result;
}
@SuppressWarnings("unchecked")
public <T> T getProxy(){
return (T) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this
);
}
private void before(){
System.out.println("Before");
}
private void after(){
System.out.println("after");
}
}
CGLib代理
public class CGLibProxy implements MethodInterceptor{
private static CGLibProxy instance = new CGLibProxy();
private CGLibProxy(){
}
public static CGLibProxy getInstance(){
return instance;
}
public <T> T getProxy(Class<T> cls){
return (T) Enhancer.create(cls,this);
}
public Object intercept(Object obj,Method method,Object[] args,MethodProxy proxy)throws Throwable{
before();
Object result = proxy.invokeSuper(obj,args);
after();
return result;
}
private void before(){
System.out.println("Before");
}
private void after(){
System.out.printin("after");
}
}