静态代理
Hello接口
public interface Hello {
void say(String name);
}
Hello实现类
public class HelloImpl implements Hello {
public void say(String name) {
System.out.println("Hello "+name);
}
}
Hello代理类
public class HelloProxy implements Hello {
private Hello hello;
public HelloProxy(){
hello = new HelloImpl();
}
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 Main {
public static void main(String[] args) {
Hello helloProxy = new HelloProxy();
helloProxy.say("world");
}
}
DynamicProxy 类
public class DynamicProxy implements InvocationHandler {
private Object target;
public DynamicProxy(Object target){
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object result = method.invoke(target,args);
System.out.println("after");
return result;
}
}
public class main {
public static void main(String[] args) {
Hello hello = new HelloImpl();
DynamicProxy dynamicProxy = new DynamicProxy(hello);
Hello helloProxy = (Hello)Proxy.newProxyInstance(
hello.getClass().getClassLoader(),
hello.getClass().getInterfaces(),
dynamicProxy
);
helloProxy.say("world");
}
}
CGLib
CGLibProxy类
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 o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before");
Object result = methodProxy.invokeSuper(o,objects);
System.out.println("after");
return result;
}
}
测试类
public class Main {
public static void main(String[] args) {
Hello helloProxy = CGLibProxy.getInstance().getProxy(HelloImpl.class);
helloProxy.say("world");
}
}