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!

最常称为VSCode的VisualStudioCode是开发人员用于编码的工具之一。Intellisense是VSCode中包含的一项功能,可让编码人员的生活变得轻松。它提供了编写代码的建议或工具提示。这是开发人员更喜欢的一种扩展。当IntelliSense不起作用时,习惯了它的人会发现很难编码。你是其中之一吗?如果是这样,请通过本文找到不同的解决方案来解决IntelliSense在VS代码中不起作用的问题。Intellisense如下所示。它在您编码时提供建议。首先检

解决C++代码中出现的“error:redefinitionofclass'ClassName'”问题在C++编程中,我们经常会遇到各种各样的编译错误。其中一个常见的错误是“error:redefinitionofclass'ClassName'”(类‘ClassName’的重定义错误)。这个错误通常出现在同一个类被定义了多次的情况下。本文将

Steam是十分受欢迎的一个平台游戏,拥有众多优质游戏,可是有些win10用户体现自己下载不了steam,这是怎么回事呢?极有可能是用户的ipv4服务器地址没有设置好。要想解决这个问题的话,你可以试着在兼容模式下安装Steam,随后手动修改一下DNS服务器,将其改成114.114.114.114,以后应当就能下载了。win10下载不了steam怎么办:WIn10下能够试着兼容模式下安装,更新后必须关掉兼容模式,不然网页将无法加载。点击程序安装的属性,以兼容模式运作运行这个程序。重启以增加内存,电

解决PHP报错:继承父类时遇到的问题在PHP中,继承是一种重要的面向对象编程的特性。通过继承,我们能够重用已有的代码,并且能够在不修改原有代码的情况下,对其进行扩展和改进。尽管继承在开发中应用广泛,但有时候在继承父类时可能会遇到一些报错问题,本文将围绕解决继承父类时遇到的常见问题进行讨论,并提供相应的代码示例。问题一:未找到父类在继承父类的过程中,如果系统无

机器学习模型的泛化能力问题,需要具体代码示例随着机器学习的发展和应用越来越广泛,人们越来越关注机器学习模型的泛化能力问题。泛化能力指的是机器学习模型对未标记数据的预测能力,也可以理解为模型在真实世界中的适应能力。一个好的机器学习模型应该具有较高的泛化能力,能够对新的数据做出准确的预测。然而,在实际应用中,我们经常会遇到模型在训练集上表现良好,但在测试集或真实

首先要了解invoke方法干什么的以及具体用途,实际你要搞清他在源码那个class文件上,他在那个包里,追根溯源。invoke方法来自Method类,可能不会像我们经常用到的基础类型包装类,以及集合类还有他们的扩展和工具类使用的那么多。但是Method类所在的包可是大名鼎鼎的反射Reflact,不是有一句话Java没有反射,那么很多框架都不会存在。我们经常new对象出来,但是new的前提是你知道你到底需要什么对象,你才能new,然而不管是代码还是现实生活都有未知性,也就是直到程序运行时受条件限制

弱监督学习中的标签获取问题,需要具体代码示例引言:弱监督学习是一种利用弱标签进行训练的机器学习方法。与传统的监督学习不同,弱监督学习只需利用较少的标签来训练模型,而不是每个样本都需要有准确的标签。然而,在弱监督学习中,如何从弱标签中准确地获取有用的信息是一个关键问题。本文将介绍弱监督学习中的标签获取问题,并给出具体的代码示例。弱监督学习中的标签获取问题简介:

强化学习中的奖励设计问题,需要具体代码示例强化学习是一种机器学习的方法,其目标是通过与环境的交互来学习如何做出能够最大化累积奖励的行动。在强化学习中,奖励起着至关重要的作用,它是代理人(Agent)学习过程中的信号,用于指导其行为。然而,奖励设计是一个具有挑战性的问题,合理的奖励设计可以极大地影响到强化学习算法的性能。在强化学习中,奖励可以被视为代理人与环境


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.