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

Case Code Analysis of Java Agent pattern

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

Share

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

Today, the editor will share with you the relevant knowledge points of Java agent mode example code analysis, the content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

1. Dynamic agent mode

Characteristics of dynamic agents:

When proxying an object, there is no need to implement the interface

The generation of the proxy object is to dynamically build the proxy object in memory using the API of JDK (we need to specify the type of interface to create the proxy object / target object)

Another name for dynamic agent: JDK agent, interface agent

2. JDK dynamic agent

Class diagram:

The Java dynamic proxy class is located under the java.lang.reflect package

Generally speaking, it mainly involves the following two categories:

1. Interface InvocationHandler: only one method public object invoke (Object obj,Method method, Object [] args) is defined in this API. In actual use, the first parameter obj generally refers to the proxy class, method is the method being proxied, and args is the parameter array of the method. This abstract method is implemented dynamically in the proxy class.

2. Proxy: this class is a dynamic proxy class

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

Returns an instance of the proxy class, which can be used as a proxy class (using methods declared in the interface of the proxy class)

The implementation steps of dynamic generation:

Create a class that implements the interface InvocationHandler, which must implement the invoke method

Create proxied classes and interfaces

Call the static method of Proxy to create a proxy class: newProxyInstance (ClassLoader loader,Class [])

Call a method through a proxy

3. JDK dynamic proxy code demonstration

For example, there is now a way to drive a car:

Public interface Moveable {void move ();}

Now there is a car:

/ / implement the Moveable interface and randomly suspend import java.util.Random;public class Car implements Moveable {@ Override public void move () {try {Thread.sleep (new Random (). NextInt (1000)); System.out.println ("car in motion");} catch (InterruptedException e) {e.printStackTrace ();}

Time proxy class:

Import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class TimeHandler implements InvocationHandler {public TimeHandler (Object target) {super (); this.target = target;} private Object target / * * @ param proxy: proxied object * @ param method: method of proxied object * @ param args: parameter of method * @ return * @ throws Throwable * return value: return value of Object method * / @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {long startTime = System.currentTimeMillis () System.out.println ("the car starts running"); method.invoke (target); long endTime = System.currentTimeMillis (); System.out.println ("the car ends, the driving time is: + (endTime-startTime) +" millisecond "); return null;}}

Test class:

Import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;public class Test {public static void main (String [] args) {Car car = new Car (); InvocationHandler h = new TimeHandler (car); Class cls = car.getClass () / * * newProxyInstanced parameters * are: classloader, implemented interface, implemented processor * / Moveable m = (Moveable) Proxy.newProxyInstance (cls.getClassLoader (), cls.getInterfaces (), h); m.move ();}}

The result of this output is:

The car began to run.

The car is running.

The car ends with a driving time of 137 milliseconds

/ / the subsequent time is random, and it is different each time.

Note:

JDK agents can only proxy classes that implement the interface, not those that do not implement the interface

These are JDK dynamic proxies and, of course, cglib dynamic proxies:

Cglib is for the class to achieve proxy, the principle of cglib is to generate a subclass of the specified target class, and override the method to achieve enhancement, but because the inheritance is used, it can not be modified by final proxy, because Xiao Ying senior himself does not fully grasp this piece, here do not explain much, you can refer to the technical articles of other bloggers.

These are all the contents of the article "Java Agent pattern example Code Analysis". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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