In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the common ways of Java dynamic agents". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What is a dynamic agent?
Dynamic proxy is a technique that creates a proxy object of the target object and makes functional enhancements to the methods in the target object while the program is running. In the process of generating the proxy object, the target object remains the same, and the method in the proxy object is the enhancement of the target object method. It can be understood that during the run, the dynamic interception of the method in the object performs functional operations before and after the intercepting method (you can also manipulate the parameters of the original method).
Proxy class during the running of the program, the proxy object created is called dynamic proxy object. In this case, the proxy object created is not defined in advance in the Java code. Instead, it is dynamically generated at run time, according to our "instructions" in the dynamic proxy object. In other words, the dynamic proxy will dynamically generate the proxy object for the object you want to get. Dynamic proxies can enhance the methods of proxied objects. With the technology of dynamic proxy, you can enhance the function of the method of the proxied object without modifying the method source code, and do whatever you want before and after the method execution.
Features: bytecode is created on demand and loaded on demand
Function: enhance the method without modifying the source code
There are two common ways of dynamic agent: 1. Dynamic Agent based on Interface
Provider: JDK
Create a proxy object using JDK's official Proxy class
Note: the target object of the proxy must implement the interface (at least one)
two。 Class-based dynamic agent
Provider: third party CGLib
Create a proxy object using the Enhancer class of CGLib
Note: the proxied class cannot be modified with final (final class). If you report an asmxxxx exception, you need to import the asm.jar package.
/ / JDK dynamic proxy (interface-based dynamic proxy) Proxy.newProxyInstance (three parameters); ClassLoader: class loader which is used to load the bytecode of the proxy object. Use the same class loader as the proxied object. (fixed writing) Class []: bytecode array it is used to make the proxy object and the delegate object have the same method. (fixed) InvocationHandler: used to provide enhanced code it allows us to write how to proxy. We usually write an implementation class of the interface, usually an anonymous inner class, but we don't have to InvocationHandler who writes the implementation class of the interface. At this time, we need to write it ourselves.
Here is an example of an actor:
A long time ago, actors and crew met directly. There is no middleman.
With the passage of time, a new profession has emerged: broker (middleman). At this time, if the crew wants to find an actor, they need to find it through an agent. Let's demonstrate it in code.
Package com.haust.service;public interface IActor {/ * basic performance * @ param money * / public void basicAct (float money); / * * dangerous performance * @ param money * / public void dangerAct (float money);} package com.haust.serviceImpl;import com.haust.service.IActor Public class Actor implements IActor {/ * an actor * / / implements an interface, which means that it has a method implementation in the interface. That is: meet the requirements of the brokerage firm @ Override public void basicAct (float money) {System.out.println ("get the money and start the basic show:" + money);} @ Override public void dangerAct (float money) {System.out.println ("get the money and start the dangerous show:" + money);}} package com.haust.test Import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import com.haust.service.IActor;import com.haust.serviceImpl.Actor;public class Client {public static void main (String [] args) {/ / A crew looking for actors: final Actor actor = new Actor () / / proxied class / * proxy: * indirect. * obtain proxy object: * requirement: * the proxied class implements at least one interface * the method of creation * Proxy.newProxyInstance (three parameters) * parameter meaning: * ClassLoader: use the same class loader as the proxied object. * Interfaces: has the same behavior as the proxied object. Implement the same interface. * InvocationHandler: how to represent. * * / / (IActor) Proxy.newProxyInstance, where the cast must be of interface type IActor proxyActor = (IActor) Proxy.newProxyInstance (actor.getClass () .getClassLoader (), actor.getClass () .getInterfaces ()) New InvocationHandler () {/ * executes any method of the proxied object Will go through this method. * this method has the function of intercepting. * * Parameter: * proxy: reference to the proxy object. It is not necessary to get * method: the currently executed method object * args: the parameters required to execute the method * return value: * the return value of the current execution of the proxied object method * / @ Override public Object invoke (Object proxy Method method, Object [] args) throws Throwable {String name = method.getName () Float money = (Float) args [0]; / / the method executed has only one parameter Object rtValue = null / / each agency charges different fees for different performances. If ("basicAct" .equals (name)) {/ / basic performances are judged here. There is no 2000 not playing if (money > 2000) {/ / it seems that the crew has given 8000, but actually only 4000 / / in the hands of the actors, that is, we have not modified the source code of the original basicAct method. The method is enhanced by rtValue = method.invoke (actor, money/2). }} if ("dangerAct" .equals (name)) {/ / dangerous performance There is no 5000 not playing if (money > 5000) {/ / it seems that the crew has given 50000 In fact, only 25000 / / in the hands of the actors, that is, we did not modify the source code of the original dangerAct method, but enhanced the method rtValue = method.invoke (actor, money/2). }} return rtValue;}}); / / when there is no agency, go directly to the actor. / / actor.basicAct (1000F); / / actor.dangerAct (5000f); / / the crew cannot contact the actors directly, but the actors proxyActor.basicAct (2000f) found by the agency; / / No proxyActor.dangerAct (5000f) if the price is less than 2000;}}
Summary:
First, you need to create an interface and then a class to implement the interface, and then proxy the class. The class must implement at least one interface.
Classes designed by dynamic proxies based on subclasses: Enhancer providers: how third-party cglib libraries create proxy objects: requirements for creating proxy objects using the create method in the Enhancer class: the proxied object is not the final class (the final class does not have subclasses) parameters of the create method: parameters of the Class method: Class: bytecode It is the bytecode callback used to specify the proxied object: used to provide enhanced code that lets us write how to proxy. We are usually an implementation class of this interface, usually an anonymous inner class, but it is not necessary. The implementation class of this interface is written by who uses it. What we generally write is the subinterface implementation class of the interface: MethodInterceptor//CGLib dynamic proxy (subclass-based dynamic proxy) Enhancer.create (two parameters)
The code is as follows:
Package com.haust.serviceImpl;public class Actor {/ / does not implement any interface / * an actor * / public void basicAct (float money) {System.out.println ("get the money, start the basic performance:" + money) } public void dangerAct (float money) {System.out.println ("get the money and start a dangerous show:" + money);}} package com.haust.test;import java.lang.reflect.Method;import org.springframework.cglib.proxy.Enhancer;import org.springframework.cglib.proxy.MethodInterceptor;import org.springframework.cglib.proxy.MethodProxy;import com.haust.serviceImpl.Actor Public class test {public static void main (String [] args) {Actor actor = new Actor () / / need to create this proxied object / * dynamic proxy based on subclass * requirement: * the proxied object cannot be the final class * the class used: * Enhancer * used Method: * create (Class Callback) * parameters of the method: * Class: bytecode of the proxied object * Callback: how to proxy * @ param args * / / the type of the forced class at this time is the type of the proxied class Actor cglibActor = (Actor) Enhancer.create (actor.getClass () New MethodInterceptor () {@ Override public Object intercept (Object proxy, Method method, Object [] args, MethodProxy methodProxy) throws Throwable {/ * executes any method of the proxied object Will go through this method. Any method of the proxied object can be enhanced within this method. * * parameters: * the first three are the same as dynamic proxies based on interfaces. * MethodProxy: the proxy object that currently executes the method. * return value: * return value of the current execution method * / String name = method.getName (); Float money = (Float) args [0]; Object rtValue = null If ("basicAct" .equals (name)) {/ / basic performance if (money > 2000) {rtValue = method.invoke (actor, money/2) }} if ("dangerAct" .equals (name)) {/ / dangerous performance if (money > 5000) {rtValue = method.invoke (actor) Money/2) }} return rtValue;}}); cglibActor.basicAct (10000); cglibActor.dangerAct (100000) This is the end of the content of "what are the common ways of Java dynamic agents". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.