1, JDK dynamic proxy implementation

Description:

Proxy: Proxy is the parent of all dynamic proxies. It provides a static method to create class objects and instances of dynamic proxies. InvocationHandler: Each dynamic proxy instance has an associated InvocationHandler. When a method is invoked on a proxy instance, the method call is forwarded to the Invoke method of InvocationHandler;Copy the code

Because JDK dynamic proxies are interface-based, create an interface first

The target class:

Strengthen the class:

The proxy class:

Tests Test classes:

Results:

2. Cglib dynamic proxy implementation

Description:

CGLIB(Code Generation Library) is a bytecode Generation Library based on ASM, which allows us to modify and dynamically generate bytecode at run time. CGLIB implements proxies by inheritance. Enhancer: specifies the target object to be proded, the object that actually handles the proxy logic, and finally gets the proxy object by calling the create() method. All calls to this object's non-final methods are forwarded to the MethodInterceptor; MethodInterceptor: Method calls to dynamic proxy objects are forwarded to the Intercept method for enhancement;Copy the code

The target class:

Strengthen the class:

The proxy class:

The test class:

Results:

JDK dynamic proxy and Cglib dynamic proxy features and differences

JDK native dynamic proxy is Java native support, does not require any external dependencies, but it can only be proxy based on interface;

2. Cglib can be proxied by inheritance, regardless of whether the target object implements the interface, but it cannot handle fiANL.