Home > Java > javaTutorial > body text

How to use Cglib proxy in java

王林
Release: 2023-04-30 18:04:07
forward
1613 people have browsed it

Explanation

1. Cglib agent can be called a subclass agent, which builds subclass objects in memory to extend the functionality of the target object.

Both static proxies and JDK proxies require an object to implement an interface. Sometimes the proxy object is just a single object, and Cglib proxy can be used at this time.

2. Cglib generates a proxy class through Enhancer and implements the intercept method by implementing the MethodInterceptor interface.

You can add enhancement methods to this method, and you can use reflection Method or MethodProxy inheritance classes to call the original method.

Example

public class TVProxyCglib implements MethodInterceptor {
 
    //给目标对象创建一个代理对象
    public Object getProxyInstance(Class c){
        //1.工具类
        Enhancer enhancer = new Enhancer();
        //2.设置父类
        enhancer.setSuperclass(c);
        //3.设置回调函数
        enhancer.setCallback(this);
        //4.创建子类(代理对象)
        return enhancer.create();
    }
 
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("TVProxyFactory enhancement.....");
        Object object = methodProxy.invokeSuper(o, objects);
        return object;
    }
}
Copy after login

The above is the detailed content of How to use Cglib 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!