Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed introduction of three Agent modes of Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the detailed introduction of the three agent modes of Java". In the daily operation, I believe many people have doubts about the detailed introduction of the three agent modes of Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "detailed introduction of the three agent modes of Java". Next, please follow the editor to study!

Agent mode

Proxy is a design pattern that provides another way to access the target object, that is, to access the target object through the proxy object. The advantage of this is that on the basis of the implementation of the target object, you can enhance the additional functional operation, that is, to extend the functionality of the target object.

Here is an idea in programming: don't modify the code or method that others have already written. If you need to modify it, you can extend the method by proxy.

The UML diagram is shown as follows:

Agent mode

Static agent

When using a static proxy, you need to define an interface or parent class. The proxied object implements the same interface or inherits the same parent class as the proxy object.

Code example:

Interface Source {void method ();} class OldClass implements Source {@ Overridepublic void method () {}} class Proxy implements Source {private Source source = new OldClass (); void doSomething () {} @ Overridepublic void method () {new Class1 () .Func1 (); source.method (); new Class2 () .Func2 (); doSomething ();} public static void main (String [] args) {Proxy proxy = new Proxy (); proxy.method ();}

Shortcomings of static agents:

Because the proxy object needs the same interface or parent class as the target object implementation, there will be many proxy classes, too many classes. At the same time, once methods are added to the interface, both the target object and the proxy object are maintained.

Dynamic agent

The dynamic proxy class in JDK only needs to use the java.lang.reflect.Proxy.newProxyInstance method, which needs to receive three parameters, which is written as follows:

Static Object newProxyInstance (ClassLoader loader, Class [] interfaces,InvocationHandler h)

Note that the method is static in the Proxy class, and the three parameters received are:

ClassLoader loader: specifies that the current target object uses a classloader, and the method to obtain the loader is a fixed Class [] interfaces: the interface type implemented by the target object, the type is confirmed by generics, and the method to obtain the interface type is fixed InvocationHandler h; event handling, when the method of the target object is executed, triggers the method of the event handler and passes in the method that currently executes the target object as a parameter

Code example:

/ * Interface * / interface IUserDao {void save ();} / * Interface implementation * Target object * / class UserDao implements IUserDao {public void save () {System.out.println ("- data saved successfully! -");}} / * create dynamic proxy object * dynamic proxy does not need to implement the interface, but needs to specify the interface type * / class ProxyFactory {/ / maintain a target object private Object target Public ProxyFactory (Object target) {this.target = target;} / / generate proxy object public Object getProxyInstance () {return Proxy.newProxyInstance (target.getClass (). GetClassLoader (), target.getClass (). GetInterfaces (), (proxy, method, args)-> {System.out.println (start transaction); / / execute target object method Object returnValue = method.invoke (target, args); System.out.println (commit transaction); return returnValue;}) }} / * Test class * / class App {public static void main (String [] args) {/ / Target object IUserDao target = new UserDao (); / / System.out.println (target.getClass ()); / / to the target object, create proxy object IUserDao proxy = (IUserDao) new ProxyFactory (target). GetProxyInstance (); / / System.out.println (proxy.getClass ()); / / proxy object execution method proxy.save ();}}

Note: the proxy object does not need to implement the interface, but the target object must implement the interface, otherwise the dynamic proxy cannot be used.

Cglib Agent

Both static proxy and dynamic proxy pattern require the target object to implement the interface, but sometimes the target object is just a single object and does not implement any interface, so you can use the class to implement the proxy as a subclass of the target object, which is called Cglib proxy.

Cglib agent, also known as subclass proxy, builds a subclass object in memory to extend the function of the target object. Cglib is a powerful high-performance code generation package that extends the Java class and implements the Java interface at run time. It is widely used by many AOP frameworks to provide methods for interception (interception), such as Spring AOP.

The bottom layer of the Cglib package is to transform bytecode and generate new classes by using a small and fast bytecode processing framework, ASM. What the Cglib subclass agent needs to note is:

1. You need to import the jar file of Cglib, but the Cglib function is already included in the core package of Spring, so you can introduce spring-core-xxx.jar directly. (Cglib is not included until after Spring 3.2)

two。 The class of the proxy cannot be final, otherwise an error will be reported

3. If the target object's method is final/static, it will not be intercepted, that is, the target object's additional business methods will not be executed.

Code example:

Public class test {public static void main (String [] args) {/ / Target object UserDao target = new UserDao (); / / proxy object UserDao proxy = (UserDao) new ProxyFactory (target). GetProxyInstance (); / / execute the method proxy.save () of the proxy object;}} / * Target object, without implementing any interface * / class UserDao {public void save () {System.out.println ("- saved data! -") }} / * Cglib subclass agent factory * dynamically build a subclass object in memory for UserDao * / class ProxyFactory implements MethodInterceptor {/ / maintain the target object private Object target;public ProxyFactory (Object target) {this.target = target;} / / create a proxy object public Object getProxyInstance () {/ / 1 for the target object. Tool class Enhancer en = new Enhancer (); / / 2. Set the parent class en.setSuperclass (target.getClass ()); / / 3. Set the callback function en.setCallback (this); / / 4. Create a subclass (proxy object) return en.create ();} @ Overridepublic Object intercept (Object obj, Method method, Object [] args, MethodProxy proxy) throws Throwable {System.out.println ("start transaction..."); / / execute the target object's method Object returnValue = method.invoke (target, args); System.out.println ("commit transaction..."); return returnValue;}}

At this point, the study on the "detailed introduction of the three agent modes of Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report