静态代理
实现方法:和目标对象继承同一个接口。
因为本质是一个class对象,所以叫静态代理。
动态代理:Proxy
必须传入接口实现的类。
public class ProxyJdk {public <T> T create(T t) {Class<?> aClass = t.getClass();Object o = Proxy.newProxyInstance(aClass.getClassLoader(),aClass.getInterfaces(), (proxy, method, args) -> {//如果要对不同方法代理不一样,可以通过method.getName()来判断System.out.println("jdk代理开始");Object invoke = method.invoke(t, args);System.out.println("jdk代理结束");return invoke;});return (T) o;}public static void main(String[] args) {// 必须用接口,否则会转换失败UserTestService userTestService = new UserTestServiceImpl();UserTestService user1 = new ProxyJdk().create(userTestService);System.out.println(user1.power(123));}}
cglib代理
可以直接传入普通对象。
CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成新的类。
import org.springframework.cglib.proxy.Enhancer;import org.springframework.cglib.proxy.MethodInterceptor;import org.springframework.cglib.proxy.MethodProxy;import java.lang.reflect.Method;public class ProxyCglib {public <T> T create(T t) {Object o = Enhancer.create(t.getClass(), new MethodInterceptor() {@Overridepublic Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {System.out.println("=====");Object invoke = method.invoke(t, objects);System.out.println("!!!!!");return invoke;}});return (T) o;}public static void main(String[] args) {User user = new User();User user1 = new ProxyCglib().create(user);user1.setName("hello");System.out.println(user1);}}
