Static and dynamic proxies

static proxy

Definition: The proxy and the proxied object are determined before proxying. They both implement the same interface or inherit the same abstract class

Two implementation mechanisms

  • inherit
  • polymerization

model:
write picture description here

Advantages and disadvantages of static proxies

Advantages: Extend the original function, do not invade the original code

Disadvantages: If it is implemented by inheritance, because the JAVA class can only inherit one parent class, it needs to have multiple proxy classes; if it is implemented by aggregation, when multiple interface proxies are to be implemented, the code will be bloated, and each proxy needs to be implemented for each proxy. Interface writing implementation code

Dynamic proxy

  • JDK dynamic proxy
  • CGLib dynamic proxy

CGLib

CGLIB (Code Generation Library) is an open source project. It is a powerful, high-performance, high-quality Code generation library. It can extend Java classes and implement Java interfaces at runtime. Hibernate uses it to realize the dynamic generation of PO (Persistent Object persistent object) bytecode;

The difference between jdk and cglib dynamic proxy implementation

  1. The performance of dynamic proxy objects created by CGLib is much higher than that of dynamic proxy objects created by JDK, but CGLib takes much more time to create proxy objects than JDK, so for singleton objects, there is no need to create objects frequently , it is appropriate to use CGLib, on the contrary, it is more appropriate to use the JDK method;
  2. The object of the JDK dynamic proxy must implement one or more interfaces;
  3. The bytecode generated in the cglib dynamic proxy is more complex, the generated proxy class is a subclass of the delegate class, and cannot handle methods modified by the final keyword;
  4. JDK uses the reflection mechanism to call the method of the delegate class, and cglib uses the index-like method to directly call the method of the delegate class;
    write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325675385&siteId=291194637