illustrate
1. The 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.
Enhancement methods can be added to the method and the original method can be called using a reflective Method or MethodProxy inherited class.
Example
public class TVProxyCglib implements MethodInterceptor { //Create a proxy object for the target object public Object getProxyInstance(Class c){ //1. Tool class Enhancer enhancer = new Enhancer(); //2.Set the parent class enhancer.setSuperclass(c); //3.Set the callback function enhancer.setCallback(this); //4. Create a subclass (proxy object) 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; } }
The above is the use of Cglib agent in java, I hope it will be helpful to everyone.
More Java learning guide: java tutorial
The operating environment of this tutorial: Windows 7 system, Java 10 version, DELL G3 computer.