Java: CGLib
作者:互联网
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency>
Code Generation Library:
package io.veer.redis.proxy; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class ProxyFactory implements MethodInterceptor{ // 注入被代理对象 private final Station station = new Station(); public static void main(String[] args){ // 创建代理对象工厂 ProxyFactory proxyFactory = new ProxyFactory(); // 获取代理对象 Station proxyObject = proxyFactory.getProxyObject(); // 调用代理对象的sell方法 proxyObject.sell(); } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable{ System.out.println("\033[37;7m" + "cglib" + "\033[0m"); // 调用被代理对象 return method.invoke(station, objects); } public Station getProxyObject(){ // 创建Enhancer对象, 类似JDK的Proxy Enhancer enhancer = new Enhancer(); // 设置父类的类对象, 指定父类 enhancer.setSuperclass(Station.class); // 设置回调函数 enhancer.setCallback(this); // 创建返回代理对象 return (Station) enhancer.create(); } } class Station{ public void sell(){ System.out.println("\033[37;7m" + "sell" + "\033[0m"); } }
标签:enhancer,sell,Java,CGLib,Station,cglib,033,public 来源: https://www.cnblogs.com/dissipate/p/16255589.html