In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
What is the use of the agent mode in Java? I believe many inexperienced people are at a loss about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Proxy mode is often encountered in actual development, and it is used in AOP and RPC of Spring. It is also necessary to learn the design idea. Understanding its principle is of great help to the work and study in the future.
The proxy pattern can be understood as extending and enhancing the function of the target object without changing the source code.
Agent mode can be divided into two types: static agent and dynamic agent; dynamic agent can be divided into JDK agent and cglib agent.
Static agent
When using a static proxy, you need to define an interface or parent class, and the proxied object implements the same interface or inherits the same parent class together with the proxy object.
Take Haitao shopping as an example, we need to find a Haitao platform for them to help us buy quality and cheap goods in overseas shopping malls, and then pay and receive the goods. The code is as follows:
First define an abstract object role.
Public interface Item {void shopping ();}
The target (proxied) object role implements the abstract object role.
Public class Person implements Item {@ Override public void shopping () {System.out.println (shopping);}}
The role of the proxy object and the role of the target (proxied) object implement the same interface, and the proxy object contains a reference to the target (proxied) object.
Public class PersonProxy implements Item {private Person person; public PersonProxy (Person person) {this.person = person;} public void begin () {System.out.println ("log on to Haitao platform, select the goods you like");} public void end () {System.out.println ("submit order, pay, wait for harvest") } @ Override public void shopping () {begin (); person.shopping (); end ();}}
Test:
Public class Ceshi {public static void main (String [] args) {Person person = new Person (); PersonProxy personProxy = new PersonProxy (person); personProxy.shopping ();}}
Running result:
Log on to Haitao platform, select the goods you like, submit orders, pay, and wait for the harvest of Process finished with exit code 0
Summary:
Static proxy is a proxy class written by ourselves, which is compiled before running, and can only represent a certain kind of situation, so it is not convenient to expand, so we need to modify the code and continue to add proxy class.
Dynamic agent JDK agent
The agent method that the agent class creates when the program is running is called a dynamic agent. In our static proxy example above, the agent class (Proxy) is self-defined and compiled before the program runs. However, dynamic proxies, proxy classes are not defined in the Java code, but are dynamically generated at run time according to our "instructions" in the Java code. Compared with the static proxy, the advantage of the dynamic proxy is that it is very convenient to deal with the functions of the proxy class without modifying the methods in each proxy class.
The package where the proxy class is located: java.lang.reflect.Proxy, you can see that the JDk proxy is implemented through Java reflection.
The JDK implementation proxy only needs to use the newProxyInstance method, but this method needs to receive three parameters, which are 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 get the loader is fixed.
The type of the interface implemented by the Class [] interfaces,: target object, confirming the type using generics
InvocationHandler h: event handling, which triggers the method of the event handler when the method of the target object is executed, passing in the method that currently executes the target object as a parameter
Agent steps:
Define an event manager class that implements the invocationHandle interface and overrides the invoke (proxy class, method being proxied, method parameter list) method.
Implement the proxied class and the interface it implements.
Call Proxy.newProxyInstance (class loader, class implementation interface, transaction handler object); generate a proxy instance.
The method is called through the proxy instance.
Create an abstract object
Public interface Animal {void living (); void eating ();}
Create a target (proxied) object
Public class Person implements Animal {@ Override public void living () {System.out.println ("falling in love");} @ Override public void eating () {System.out.println ("breakfast");}}
Create a proxy generator
Public class ProxyInstance implements InvocationHandler {private Object target; public Object createProxy (Object target) {this.target = target; Object o = Proxy.newProxyInstance (target.getClass (). GetClassLoader (), target.getClass (). GetInterfaces (), this); return o;} public void begin () {System.out.println ("get up");} public void end () {System.out.println ("sleep") } @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {begin (); Object obj = method.invoke (target, args); end (); return obj;}}
test
@ Testpublic void demo () {Person person = new Person (); Animal proxy = (Animal) new ProxyInstance () .createProxy (person); proxy.living (); proxy.eating ();}
Result
Get up, fall in love, go to bed, get up, have breakfast and go to bed Process finished with exit code 0
From the above, we can see that the JDK agent can dynamically enhance the agent for different methods. (to enhance the agent for eating and living, which is different from the static agent, you need to enhance the agent manually for different methods)
Let's try another class.
Public class Cat implements Animal {@ Override public void living () {System.out.println ("basking in the sun");} @ Override public void eating () {System.out.println ("eating cat food");}} public class Dog implements Animal {@ Override public void living () {System.out.println ("breaking home") @ Override public void eating () {System.out.println ("eat dog food");}}
test
@ Testpublic void demo1 () {Cat cat = new Cat (); Animal proxy = (Animal) new ProxyInstance () .createProxy (cat); proxy.living (); proxy.eating ();} @ Testpublic void demo2 () {Dog dog = new Dog (); Animal proxy = (Animal) new ProxyInstance () .createProxy (dog); proxy.living (); proxy.eating ();}
Result
Get up, bask in the sun, get up, eat cat food, sleep Process finished with exit code 0 get up, break down, get up, eat dog food, go to bed Process finished with exit code 0
As you can see from the above, JDK agents can dynamically generate proxy objects for different classes.
Principle:
The JDK proxy dynamically generates the proxy object according to the class name through the implementation of the interface and reflection, and enhances the corresponding method by the dynamically generated proxy object according to the method name. (please refer to the source code)
Cglib Agent
Dynamic proxy pattern requires that the target object is the target object that implements an interface, but sometimes the target object is just a single object and does not implement any interface. At this time, you can use the class to implement the proxy as a subclass of the target object. This method is called cglib proxy.
Cglib agent, also known as subclass agent, constructs a subclass object in memory to extend the function of the target object.
JDK's dynamic proxy has a limitation that objects that use dynamic proxies must implement one or more interfaces. If you want to proxy classes that do not implement interfaces, you can use cglib implementation.
Cglib is a powerful high-performance code generation package that extends java classes and implements java interfaces at run time. It is widely used by many AOP frameworks, such as Spring AOP and synaop, to provide methods for interception (interception)
The bottom layer of the cglib package is to convert bytecode and generate new classes by using a small and block bytecode processing framework ASM. Direct use of ASM is discouraged because it requires you to be familiar with the internal structure of JVM, including the format of class files and instruction sets.
Cglib subclass proxy implementation method:
1. The jar file of cglib needs to be introduced, and the cglib function is already included in the core package of Spring.
two。 With the introduction of the feature pack, subclasses can be dynamically built in memory.
3. The class of the proxy cannot be final, otherwise an error is reported.
4. If the method of the target object is final/static, the proxy cannot be implemented.
Create the target class without implementing the interface
Public class Person {public void living () {System.out.println ("falling in love");}
Create a proxy object
Import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;import java.lang.reflect.Method;public class CglibProxy implements MethodInterceptor {/ / Target object private Object target; public CglibProxy (Object target) {this.target = target;} / / the method to generate the proxy object public Object createProxy () {Enhancer enhancer = new Enhancer () Enhancer.setSuperclass (target.getClass ()); enhancer.setCallback (this); Object o = enhancer.create (); return o;} / / strengthen public void begin () {System.out.println ("get up") before the target method;} / / strengthen public void end () {System.out.println ("sleep") after the target method } @ Override public Object intercept (Object o, Method method, Object [] objects, MethodProxy methodProxy) throws Throwable {begin (); / / Agent executes target method Object invoke = method.invoke (target, objects); end (); return invoke;}}
test
Public class Demo {@ Test public void test () {Person p = new Person (); Person proxy = (Person) new CglibProxy (p). CreateProxy (); proxy.living ();}}
Result
Get up, fall in love and go to bed Process finished with exit code 0
Add other methods to the Person class
Public class Person {public void living () {System.out.println ("falling in love");} public void working () {System.out.println ("go to work");}}
test
Public class Demo {@ Test public void test () {Person p = new Person (); Person proxy = (Person) new CglibProxy (p). CreateProxy (); proxy.living (); proxy.working ();}}
Result
Get up, fall in love, get up, go to work, go to bed Process finished with exit code 0
Let's try some other classes to see if we can implement the proxy as well.
Public class Cat {public void living () {System.out.println ("basking in the sun");} public void working () {System.out.println ("catching mice");}}
test
Public class Demo {@ Test public void test () {Person p = new Person (); Person proxy = (Person) new CglibProxy (p) .createProxy (); proxy.living (); proxy.working ();} @ Test public void test1 () {Cat cat = new Cat (); Cat proxy = (Cat) new CglibProxy (cat). CreateProxy (); proxy.living () Proxy.working ();}}
Result
Get up, bask in the sun, go to bed, get up, catch mice and go to bed Process finished with exit code 0. After reading the above contents, have you mastered the useful method of the agent mode in Java? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.