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

How to implement CGLIB dynamic proxy in java

PHPz
Release: 2023-05-11 10:49:06
forward
1441 people have browsed it

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;
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template