Person接口:
/**
* Created by kaizige on 2017/8/27.
*/
public interface Person {
public void walk();
}
Person实现类:
/**
* Created by kaizige on 2017/8/27.
*/
public class PersonImpl implements Person {
public void walk() {
System.out.println("walk");
}
}
动态代理类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by kaizige on 2017/8/27.
*/
public class DynaticProxy implements InvocationHandler {
private Object object;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object res=method.invoke(object,args);
after();
return res;
}
public DynaticProxy(Object object){
this.object=object;
}
private void before(){
System.out.println("before");
}
private void after(){
System.out.println("after");
}
public <T> T getProxy(){
return (T) Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
}
}
上面的动态代理类只能对有接口的类进行代理,若要对没有接口的类进行代理,则需要使用CGLib动态代理。
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* Created by kaizige on 2017/8/27.
*/
public class CGLibProxy implements MethodInterceptor {
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
before();
Object res=methodProxy.invokeSuper(o,args);
after();
return res;
}
public <T> T getProxy(Class<T> cls){
return (T) Enhancer.create(cls,this);
}
private void before(){
System.out.println("before");
}
private void after(){
System.out.println("after");
}
}
测试类:
/**
* Created by kaizige on 2017/8/27.
*/
public class Main {
public static void main(String[] args) {
DynaticProxy proxy=new DynaticProxy(new PersonImpl());
Person p=proxy.getProxy();
p.walk();
CGLibProxy proxy1=new CGLibProxy();
People people=proxy1.getProxy(People.class);
people.walk();
CGLibProxy proxy2=new CGLibProxy();
Person person=proxy2.getProxy(PersonImpl.class);
person.walk();
}
}