Home  >  Article  >  Java  >  How to implement CGLIB dynamic proxy in java

How to implement CGLIB dynamic proxy in java

PHPz
PHPzforward
2023-05-11 10:49:061414browse

1. Description

CGLIB is a powerful, high-performance code generation package. It provides proxies for classes that do not implement interfaces and provides a good complement to the JDK's dynamic proxy.

CGLIB is a package provided by a third party, so the coordinates of the jar package need to be introduced:

2, Example

public class HelloWorld {
    public static void main(String[] args) {
        // 创建代理工厂对象
        ProxyFactory factory = new ProxyFactory();
        
        // 获取代理对象
        TrainStation proxyObject = factory.getProxyObject();
        
        proxyObject.sell();
    }
}
 
// 火车站,火车站具有卖票功能
class TrainStation {
    public void sell() {
        System.out.println("火车站卖票");
    }
}
 
// 代理工厂
public class ProxyFactory implements MethodInterceptor {
    private TrainStation target = new TrainStation();
 
    public TrainStation getProxyObject() {
        // 创建Enhancer对象,类似于JDK动态代理的Proxy类,下一步就是设置几个参数
        Enhancer enhancer = new Enhancer();
        
        // 设置父类的字节码对象
        enhancer.setSuperclass(target.getClass());
        
        // 设置回调函数
        enhancer.setCallback(this);
        
        // 创建代理对象
        TrainStation obj = (TrainStation) enhancer.create();
        
        return obj;
    }
    
    public TrainStation intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        /**
         * intercept方法参数说明:
         *  o:代理对象
         *  method:真实对象中的方法的Method实例
         *  args:实际参数
         *  methodProxy:代理对象中的方法的method实例
         */
        
        System.out.println("代理点收取一些服务费用(CGLIB动态代理)");
        
        TrainStation result = (TrainStation) methodProxy.invokeSuper(o, args);
        
        return result;
    }
}

The above is the detailed content of How to implement CGLIB dynamic proxy in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete