Tutorial on implementing dynamic proxy in Java
The following content is partially based on content on the Internet. I would like to express my gratitude to the original author!
The key to realizing dynamic proxy in Java is these two things: Proxy and InvocationHandler. Let’s start with the invoke method in the InvocationHandler interface and briefly explain how Java implements dynamic proxy. N i First, the integrity of the Invoke method is as follows: java code
-
method.invoke(obj, args);
return null; , First of all, guess that Method is the method of calling, that is, the method that needs to be executed; ARGS is the parameter of the method; proxy, what is this parameter? The above implementation of the invoke() method is a relatively standard form. We see that the proxy parameter is not used here. View the description of Proxy in the JDK documentation, as follows: - Java code
A method invocation on a proxy instance through one of its pr oxy interfaces will be dispatched to the invoke method of the instance’s invocation handler, passing the proxy instance, a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.
For the convenience of explanation, here is a simple example to implement dynamic proxy.
public interface Subject {
- public
- void request();
}
//Real role: Implemented the Subject’s request() method
public class RealSubject implements Subject{
public void request(){
System.out.println("From real subject.");
}
}
Java code
-
public
class DynamicSubject - implements In vocationHandler
{
-
- }
- public DynamicSubject(Object obj)
- {
-
this.obj = ob j;
- }
-
-
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable -
{
-
System.out.println( "before calling " + method);
- method.invoke(obj, args); //-----> See the next article for details on this step. Java calls a certain function through the reflection mechanism You will understand the methods of each class after reading them.
- System.out.println( "after calling " + method);
- return
null;
}
)
//Client: generated a proxy instance and called the request() method
public class Client {
public static void main(String [] args) throws Throwable{
Subject rs=new RealSubject();//Specify the proxy here Class
- InvocationHandler ds=
- new DynamicSubject(rs);
Class> cls=rs.getClass();
- //The following is a one-time use Generate proxy
Interfaces(), ds);
- /Here it can be proved through the running results that the subject is an instance of Proxy. This instance implements the Subject interface
- System.out.println(subject
instanceof Proxy);
//Here It can be seen that the subject's Class class is $Proxy0. This $Proxy0 class inherits Proxy and implements the Subject interface.
toString());
System.out.print("The attributes in subject are: "); [] field=subject.getClass() .getDeclaredFields();
-
- System.out.print( "n"+
- " The methods in subject are: "); ().getDeclaredMethods( );
- "n"+
"subject’s parent class is: "+subject.getClass().getSuperclass());
-
System. out.print(
"n"+ "The interface implemented by subject is: "); -
Class>[] interfaces=subject.getClass().getInterfaces();
}
System.out.println("nn"+"The operation result is: "); Subject.request();
} - )
- The running results are as follows: the package name is omitted here, * **Instead of
true subject’s Class class is: class $Proxy0 The attributes in
subject are: m1, m3, m0, m2, methods in subject are: request , hashCode, equals, toString,
- The running result is:
- before calling public abstract void ***.Subject.request()
- From real subject.
- after calling public abstract void ***.Subject.re quest( )
- PS: The information of this result is very important, at least to me. Because the root cause of my confusion about dynamic proxy is that I misunderstood the subject.request() above. At least I was confused by the surface. I did not find the connection between the subject and Proxy. I was entangled in the last call of request( ) is connected with invoke(), and how does invoke know that request exists. In fact, the above true and class $Proxy0 can solve many questions. Together with the source code of $Proxy0 mentioned below, it can completely solve the doubts about dynamic proxy.
- From the code in the Client, we can use the newProxyInstance method as a breakthrough. Let’s first take a look at the source code of the newProxyInstance method in the Proxy class:
Java code public static Object newProxyInstance(ClassLoader loader, Class>[] interfaces, InvocationHandler h) throws IllegalArgumentException { if (h == null) { throw new NullPointerException(); } /* * Look up or generate the designated proxy class. */ Class cl = getProxyClass(loader, interfaces); /* * Invoke its constructor with the designated invocation handler. */ try { /* * Proxy源码开始有这样的定义: * private final static Class[] constructorParams = { InvocationHandler.class }; * cons即是形参为InvocationHandler类型的构造方法 */ Constructor cons = cl.getConstructor(constructorParams); return (Object) cons.newInstance(new Object[] { h }); } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); } catch (IllegalAccessException e) { throw new InternalError(e.toString()); } catch (InstantiationException e) { throw new InternalError(e.toString()); } catch (InvocationTargetException e) { throw new InternalError(e.toString()); } } class Proxy{ InvocationHandler h=null; protected Proxy(InvocationHandler h) { } ... } Let’s take a look at the source code of $Proxy0 which inherits Proxy:
Proxy.newProxyInstance(ClassLoader loader, Class>[] interfaces, InvocationHandler h) does the following things.
(1) According to the parameters loader and interfaces calling method getProxyClass(loader, interfaces) creates the proxy class $Proxy0. The $Proxy0 class implements the interfaces interface and inherits the Proxy class.
(2) Instantiate $Proxy0 and pass the DynamicSubject in the constructor, and then call $Proxy0 The constructor of the parent class Proxy assigns a value to h as follows:
Java code
The above is the detailed content of Tutorial on implementing dynamic proxy in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solve the "error:redefinitionofclass'ClassName'" problem in C++ code. In C++ programming, we often encounter various compilation errors. One of the common errors is "error:redefinitionofclass 'ClassName'" (redefinition error of class 'ClassName'). This error usually occurs when the same class is defined multiple times. This article will

The clustering effect evaluation problem in the clustering algorithm requires specific code examples. Clustering is an unsupervised learning method that groups similar samples into one category by clustering data. In clustering algorithms, how to evaluate the effect of clustering is an important issue. This article will introduce several commonly used clustering effect evaluation indicators and give corresponding code examples. 1. Clustering effect evaluation index Silhouette Coefficient Silhouette coefficient evaluates the clustering effect by calculating the closeness of the sample and the degree of separation from other clusters.

Steam is a very popular game platform with many high-quality games, but some win10 users report that they cannot download steam. What is going on? It is very likely that the user's IPv4 server address is not set properly. To solve this problem, you can try to install Steam in compatibility mode, and then manually modify the DNS server to 114.114.114.114, and you should be able to download it later. What to do if Win10 cannot download Steam: Under Win10, you can try to install it in compatibility mode. After updating, you must turn off compatibility mode, otherwise the web page will not load. Click the properties of the program installation to run the program in compatibility mode. Restart to increase memory, power

Known for its powerful performance and versatile features, the iPhone is not immune to the occasional hiccup or technical difficulty, a common trait among complex electronic devices. Experiencing iPhone problems can be frustrating, but usually no alarm is needed. In this comprehensive guide, we aim to demystify some of the most commonly encountered challenges associated with iPhone usage. Our step-by-step approach is designed to help you resolve these common issues, providing practical solutions and troubleshooting tips to get your equipment back in peak working order. Whether you're facing a glitch or a more complex problem, this article can help you resolve them effectively. General Troubleshooting Tips Before delving into specific troubleshooting steps, here are some helpful

Solving PHP errors: Problems encountered when inheriting parent classes In PHP, inheritance is an important feature of object-oriented programming. Through inheritance, we can reuse existing code and extend and improve it without modifying the original code. Although inheritance is widely used in development, sometimes you may encounter some error problems when inheriting from a parent class. This article will focus on solving common problems encountered when inheriting from a parent class and provide corresponding code examples. Question 1: The parent class is not found. During the process of inheriting the parent class, if the system does not

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

The label acquisition problem in weakly supervised learning requires specific code examples. Introduction: Weakly supervised learning is a machine learning method that uses weak labels for training. Different from traditional supervised learning, weakly supervised learning only needs to use fewer labels to train the model, rather than each sample needs to have an accurate label. However, in weakly supervised learning, how to accurately obtain useful information from weak labels is a key issue. This article will introduce the label acquisition problem in weakly supervised learning and give specific code examples. Introduction to the label acquisition problem in weakly supervised learning:

The generalization ability of machine learning models requires specific code examples. With the development and application of machine learning becoming more and more widespread, people are paying more and more attention to the generalization ability of machine learning models. Generalization ability refers to the prediction ability of a machine learning model on unlabeled data, and can also be understood as the adaptability of the model in the real world. A good machine learning model should have high generalization ability and be able to make accurate predictions on new data. However, in practical applications, we often encounter models that perform well on the training set, but fail on the test set or real
