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

Example Analysis of dynamic Agent and static Agent in Java

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

Share

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

This article mainly introduces the Java dynamic agent and static agent example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor with you to understand.

0. Agent mode

Why learn the agent model? This is the underlying layer of SpringAOP [SpringAOP and SpringMVC]

Classification of agent patterns:

Static agent

Dynamic agent

1. Static agent

In static proxies, the enhancements to each method of the target object are done manually (the code _ will be demonstrated later) and are very inflexible (for example, once the interface adds new methods, both the target object and the proxy object have to be modified) and troublesome (_ need to write a separate proxy class for each target class). There are very few practical application scenarios, and there are few scenarios in which static proxies are used in daily development.

Role Analysis:

Abstract roles: interfaces or abstract classes are generally used to solve the problem

Real role: the role of the delegate

Agent role: agent real role, after acting real role, we usually do some ancillary operations

Customer: the person who accesses the proxy object!

Code steps:

1. Interface

Public interface Rent {public void rent ();}

2. Real character

/ / landlord public class Host implements Rent {public void rent () {System.out.println ("landlord wants to rent a house");}}

3. Agent role

Public class Proxy implements Rent {private Host host; public Proxy () {} public Proxy (Host host) {this.host = host;} public void rent () {seeHouse (); host.rent (); fare ();} / / public void seeHouse () {System.out.println ("intermediary shows you the house") } / / collect intermediary fee public void fare () {System.out.println ("intermediary fee");}}

4. Customer server access agent role

Public class Client {public static void main (String [] args) {Host host = new Host (); / / Agent, the agent role usually has ancillary actions! Proxy proxy = new Proxy (host); proxy.rent ();}}

Benefits of the agent model:

Can make the operation of the real character more pure! You don't have to pay attention to some public business.

The public will be handed over to the agent role! Realize the division of business!

When public business is expanded, it is convenient for centralized management!

Disadvantages:

A real role produces a proxy role; from a JVM perspective, static proxies turn interfaces, implementation classes, and proxy classes into actual class files at compile time.

2. Deepen understanding

AOP, the underlying proxy mode

3. Dynamic agent

Dynamic proxy is the same as static proxy role

The agent class of the dynamic agent is dynamically generated, not written by us directly!

Dynamic agents are divided into two categories: interface-based dynamic agents and class-based dynamic agents.

Based on interface-- JDK dynamic agent

Based on class: cglib dynamic proxy

Java bytecode implementation: javasist

You need to know two classes: Proxy: proxy class, InvocationHandler: call handler

From a JVM perspective, dynamic agents generate class bytecode dynamically at run time and load it into JVM.

/ / Proxy generates dynamic proxy classes, provides static methods for creating dynamic proxy classes and instances, and is a superclass for all dynamic proxy classes created by these methods. / / InvocationHandler-- invoke calls the handler and returns the interface, which is implemented by the call handler of the proxy instance.

Benefits of dynamic agents:

Can make the operation of the real character more pure! You don't have to do some public business.

The public will be handed over to the agent role! Realize

Public static Object newProxyInstance (ClassLoader loader, Class [] interfaces, InvocationHandler h) {}

1.loader: class loader for loading proxy objects.

2.interfaces: some interfaces implemented by the proxy class

3.h: an object that implements the InvocationHandler interface

To implement a dynamic proxy, you must also implement InvocationHandler custom processing logic. When our dynamic proxy object calls a method, the call to that method is forwarded to the invoke method that implements the InvocationHandler interface class.

Public interface InvocationHandler {Object invoke (Object proxy, Method method, Object [] args) throws Throwable;}

1.proxy: dynamically generated proxy class

2.method: corresponds to the method called by the proxy class object

3.args: the parameter of the current method method

Examples of dynamic agents

1. Define the interface

Public interface Rent {public void rent ();}

2. Realize the interface of renting a house

Public class Host implements Rent {@ Override public void rent () {System.out.println ("landlord wants to rent");}}

3. Define a JDK dynamic proxy class

Real object in public class DebugInvocationHandler implements InvocationHandler {/ * proxy class * / private final Object target; public DebugInvocationHandler (Object target) {this.target = target } / * this method is actually called when you use the proxy object to call the method * / @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {/ / before calling the method System.out.println ("before method" + method.getName ()); Object res = method.invoke (target, args) / / System.out.println ("after method" + method.getName ()) after the method is called; return res;}}

Invoke () method: when our dynamic proxy object calls the native method, it actually calls the invoke () method, and then the invoke () method invokes the native method of the proxied object instead of us.

4. Get the factory class of the proxy object

Public class JdkProxyFactory {public static Object getProxy (Object target) {return Proxy.newProxyInstance (target.getClass () .getClassLoader (), target.getClass () .getInterfaces (), new DebugInvocationHandler (target));}}

GetProxy (): get the proxy object of a class mainly through the Proxy.newProxyInstance () method

5. Practical use

Public static void main (String [] args) {/ / Rent rent = new Host (); / / Rent rentProxy= (Rent) Proxy.newProxyInstance (rent.getClass (). GetClassLoader (), rent.getClass (). GetInterfaces (), new DebugInvocationHandler (rent)); Rent rentProxy= (Rent) JdkProxyFactory.getProxy (new Host ()); rentProxy.rent ();}

Run the output of the above agent

Before methodrent

The landlord wants to rent a house

After methodrent

Thank you for reading this article carefully. I hope the article "sample Analysis of dynamic and static agents in Java" shared by the editor will be helpful to you. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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