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

What is static agent and dynamic agent?

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 "what is static agent and dynamic agent". In daily operation, I believe that many people have doubts about what is static agent and dynamic agent. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is static agent and dynamic agent"! Next, please follow the editor to study!

The opening.

A middle-aged man in a blue shirt, jeans and a white thermos cup sits across from you in a hurry. It seems that the things on the project are very urgent, and it is estimated that the interview will not be too long. (then I was slapped in the face.)

The interview begins.

Interviewer: young man, I see your resume says that you are proficient in java basics, right? let me ask you a few java basics first.

All right, ask the interviewer. I was overjoyed when I heard the simple word.

Interviewer: do you know there is an agent in Java?

Know, the agent is through the agent object to access the actual target object, for example, we rent a house in life, we can directly find the landlord, but also through some rental platform to rent, through the rental platform this way is the agent. In java, this kind of rental platform is called proxy class, which can not only achieve the target object, but also add some additional functions. As far as I know, there are static and dynamic proxies in java. There is a good chance that the interviewer will ask you about these two agency modes at this time.

Interviewer: I didn't think you could understand the code through the phenomena in your life. Yes, I see you mentioned static agent and dynamic agent, so tell me what static agent is.

(sure enough, but luckily I prepared) the static proxy exists before the code runs. Or take the above rental as an example, a general rental interface will be created first in the code:

Public interface Room {void rent ();}

Then you need to have a proxied class (or real class) and a proxy class:

Public class RealRoom implements Room {private String roomname; public RealRoom (String roomname) {this.roomname = roomname;} public void rent () {System.out.println ("rented" + roomname);}

The proxy classes are as follows:

Public class ProxyClass implements Room {RealRoom realRoom; public ProxyClass (RealRoom realRoom) {this.realRoom = realRoom;} public void rent () {System.out.println ("charge intermediary fee before renting"); realRoom.rent (); System.out.println ("charge service fee after renting");}}

The proxy class can add functionality without changing the proxied object. Finally, let's test the static proxy:

Public class Main {public static void main (String [] args) {RealRoom realRoom = new RealRoom (country Garden); ProxyClass proxyClass=new ProxyClass (realRoom); proxyClass.rent ();}}

Then observe the results:

Charge an intermediary fee before renting a house and charge a service fee after renting a house in country Garden.

Interviewer: since the static agent is so powerful, what are his shortcomings?

Because the static proxy already exists before the code runs, it is necessary to build a proxy class for each proxy object, and when there are many objects that need to be proxied, we need to create a lot of proxy classes, which seriously reduces the maintainability of the program. This problem can be solved with dynamic agents.

Interviewer: then tell me something about dynamic agency

Dynamic proxy means that the proxy class is not written in the code, but generated in the process of running. Java provides two ways to implement dynamic proxy, which are dynamic proxy based on Jdk and dynamic proxy based on Cglib.

Interviewer: I forgot about the dynamic agent based on JDK. Please review it for me.

(me? To implement the dynamic proxy of Jdk, you need to implement the InvocationHandler interface, and then implement the invoke method in it. If the agent's method is called, the agent notifies and forwards it to the internal InvocationHandler implementation class invoke, which handles the content.

Public class ProxyHandler implements InvocationHandler {Object object; public ProxyHandler (Object object) {this.object = object;} / / proxy proxy object / / parameters of the method / / args method to be implemented by method public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System.out.println ("before proxy execution:" + method.getName ()); Object invoke = method.invoke (object, args) System.out.println ("after Agent execution:" + method.getName ()); return invoke;}}

Next, execute the dynamic proxy in the main method

Public static void main (String [] args) {Room room=new RealRoom (country Garden); / / obj.getClass () .getClassLoader () class loader / / obj.getClass () .getInterfaces () Interface / / InvocationHandler object InvocationHandler invocationHandler=new ProxyHandler (room) implemented by the target class; Room proxyRoom = (Room) Proxy.newProxyInstance (room.getClass (). GetClassLoader (), room.getClass (). GetInterfaces (), invocationHandler); proxyRoom.rent ();}

The core of this code is Proxy.newProxyInstance, which aims to generate the proxy class at run time, and finally execute the proxied method through the proxy class. The final results are as follows:

Before agent execution: after rent rents country Garden agent execution: rent

Interviewer: now that you say that, I think of dynamic agency. what are his advantages?

When I talked about static proxies earlier, I said that the disadvantage of static proxies is that for each proxied object, you need to build a proxy class. Because static agents are written before the project runs. This is not the case with dynamic proxies, because dynamic proxies create proxy classes only at run time, so you only need to write a dynamic proxy class. For example, I create an agent to sell the house:

Write a general interface Sell

Public interface Sell {void sellRoom ();}

Then write a class of the proxied object:

Public class RealSell implements Sell {public void sellRoom () {System.out.println ("sold the house");}}

Next, execute the dynamic proxy in the main method

Public static void main (String [] args) {Sell sell=new RealSell (); InvocationHandler invocationHandler=new ProxyHandler (sell); Sell proxysell= (Sell) Proxy.newProxyInstance (sell.getClass (). GetClassLoader (), sell.getClass (). GetInterfaces (), invocationHandler); proxysell.sellRoom ();}

The final implementation results are as follows:

Before the agent executes: sellRoom sells the house after the agent executes: sellRoom

Through dynamic proxy, I can proxy multiple objects through a dynamic proxy class.

Interviewer: if I remember correctly, you can only have a proxy interface in this way. I think your above examples are all proxy interfaces, so what should I do if I want to act as a proxy class?

It is true that jdk dynamic proxies can only proxy interfaces. JDK dynamic proxies are interface-based, in other words, both the proxy class and the target class implement the same interface. If you want a proxy class, you can use the CGLib,CGLib dynamic proxy class to inherit the target class, and then implement the methods of the target class.

Create a target class CGRoom

Public class CGRoom {public void rent (String roomName) {System.out.println (rented + roomName);}}

Create a dynamic proxy class of cglib, inherit MethodInterceptor, and implement the intercept method in it

Public class MyMethodInterceptor implements MethodInterceptor {public Object intercept (Object o, Method method, Object [] objects, MethodProxy methodProxy) throws Throwable {System.out.println ("before Agent execution: + method.getName ()); Object object=methodProxy.invokeSuper (ocharge objects); System.out.println (" after Agent execution: + method.getName ()); return object;}} "

Finally, create the proxy class through the enhance object

Public static void main (String [] args) {/ / create the Enhancer object, which is similar to the Proxy class of the JDK dynamic proxy. The next step is to set several parameters Enhancer enhancer=new Enhancer (); / / set the bytecode file enhancer.setSuperclass (CGRoom.class) of the target class; / / set the callback function enhancer.setCallback (new MyMethodInterceptor ()); / / create the proxy object CGRoom proxy= (CGRoom) enhancer.create () Proxy.rent (country Garden);}

Finally, the following results are achieved:

Before agent execution: after rent rents country Garden agent execution: rent

Interviewer: since the dynamic agent is so awesome, do you use it in your daily work?

Usually, although dynamic proxies are hardly used in my business code, dynamic proxies are used in the Spring series framework I use in my work, as well as in the RPC framework. Take AOP as an example, AOP enhances the target object through dynamic proxies, such as pre-notification, post-notification, and so on.

Interviewer: not bad! Here are a few basics for you to talk about your understanding of the notes and what problems have been solved by the notes?

Classes, methods, variables, parameters and packages in the Java language can all be marked with annotations. We can get the corresponding comments and the contents defined in the annotations when the program is running. For example, if it is detected in Spring that your class is marked by @ Component annotations, the Spring container will classify the class as self-management at startup, so you can inject the object with @ Autowired annotations.

Interviewer: do you know how to define annotations yourself?

Yes, there are four main steps to customize annotations:

The first step is to annotate the @ interface declaration:

Public @ interface Myannotation {String key () default "";}

The second step is to modify the notes with four meta-annotations: (just say these four notes during the interview)

Meta-annotations are responsible for other annotations. There are four meta-annotations in java, which are @ Target,@Retention,@Documented,@Inherited. The following four kinds of annotations are introduced first:

@ Target:Target describes the scope of the object modified by the annotation. The values (ElementType) are:

Used to describe the constructor

Used to describe attributes

Used to describe local variables

Used to describe the method

Used to describe the package

Used to describe parameters

Used to describe classes, interfaces (including annotation types), or enum declarations

@ Retention:Retention defines the retention range of annotations. The values (RetentionPoicy) are:

Valid in the source file (that is, source file retention)

Valid in class files (that is, class retention)

Valid at run time (that is, retained at run time)

Documented:Documented is used to describe other types of annotation that should be used as the public API of annotated program members, so they can be documented by tools such as javadoc. Documented is a tag comment and has no members.

The @ Inherited:Inherited meta-annotation is a tag annotation, and @ Inherited states that a certain annotated type is inherited. If an annotation type with the @ Inherited modifier is used for a class, the annotation will be used for a subclass of that class.

@ Target ({ElementType.METHOD,ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inheritedpublic @ interface Myannotation {String key () default "";}

The third step uses annotations, because MEHTOD and FIELD are defined when Target is defined, so you can use this annotation in properties and methods:

Public class MyannotationTest {@ Myannotation (key = "javayz") private String username;}

The fourth step is to use reflection to analyze the annotation.

Public static void main (String [] args) {Class myclass=MyannotationTest.class; Field [] fields = myclass.getDeclaredFields (); for (Field field: fields) {if (field.isAnnotationPresent (Myannotation.class)) {System.out.println ("Custom annotations configured"); Myannotation annotation = field.getAnnotation (Myannotation.class) Note key on System.out.println ("attribute:" + field.getName () + "is" + annotation.key ());} "

Output result:

A custom annotation attribute is configured: the annotation key on username is javayz

Interviewer: I see you mentioned reflex in step 4 above, right? Then tell me what a reflection is and what its characteristics are:

JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic acquisition of information and the ability to dynamically call the methods of the object is called the reflection mechanism of the java language.

In the fourth step above, using reflection to parse the annotation, I got the class object of MyannotationTest through MyannotationTest.class, and then used myclass.getDeclaredFields (); to get all the properties. This is the reflex.

At this point, the study of "what is static agent and dynamic agent" 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