This article mainly introduces the detailed interpretation of the Java Proxy mechanism. It is still very good. I share it with everyone here. Friends who need it can refer to it.
Dynamic proxy is actually the java.lang.reflect.Proxy class that dynamically generates a class byte based on all the interfaces you specify. This class will inherit the Proxy class and implement all the interfaces you specify (you specify it in the parameters The interface array passed in); then use the classloader you specified to load the class byte into the system, and finally generate an object of such a class, and initialize some values of the object, such as invocationHandler, to the Method members corresponding to all interfaces. After initialization, the object is returned to the calling client. In this way, what the client gets is a Proxy object that implements all your interfaces. Please see the example analysis:
1 Business interface class
public interface BusinessProcessor { public void processBusiness(); }
2 Business implementation class
public class BusinessProcessorImpl implements BusinessProcessor { public void processBusiness() { System.out.println("processing business....."); } }
Three business agent classes
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class BusinessProcessorHandler implements InvocationHandler { private Object target = null; BusinessProcessorHandler(Object target){ this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("You can do something here before process your business"); Object result = method.invoke(target, args); System.out.println("You can do something here after process your business"); return result; } }
Four client application classes
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { BusinessProcessorImpl bpimpl = new BusinessProcessorImpl(); BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl); BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(), bpimpl.getClass().getInterfaces(), handler); bp.processBusiness(); } }
Now let’s look at the print results:
You can do something here before process your business processing business..... You can do something here after process your business
Through the results, we can easily see the role of Proxy. It can do some auxiliary work you want before and after your core business methods, such as log logs, security mechanisms, etc.
Now let’s analyze how the above class works.
There is nothing much to say about Category 1 and 2. Let’s look at category three first. Implements the invoke method of the InvocationHandler interface. In fact, this class is the fixed interface method ultimately called by Proxy. Proxy does not matter how the client's business method is implemented. When the client calls Proxy, it will only call the invoke interface of InvocationHandler, so our actual implemented method must be called in the invoke method. The relationship is as follows:
BusinessProcessorImpl bpimpl = new BusinessProcessorImpl(); BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl); BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(....); bp.processBusiness()-->invocationHandler.invoke()-->bpimpl.processBusiness();
So what kind of object is bp? Let’s change the main method and take a look:
public static void main(String[] args) { BusinessProcessorImpl bpimpl = new BusinessProcessorImpl(); BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl); BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(), bpimpl.getClass().getInterfaces(), handler); bp.processBusiness(); System.out.println(bp.getClass().getName()); }
Output result:
You can do something here before process your business processing business..... You can do something here after process your business $Proxy0
bp turns out to be an object of the $Proxy0 class. So what does this class look like? OK Let's write two more methods to print out this class and see what it is. What is it with three heads and six arms? We write the following two static methods below main.
public static String getModifier(int modifier){ String result = ""; switch(modifier){ case Modifier.PRIVATE: result = "private"; case Modifier.PUBLIC: result = "public"; case Modifier.PROTECTED: result = "protected"; case Modifier.ABSTRACT : result = "abstract"; case Modifier.FINAL : result = "final"; case Modifier.NATIVE : result = "native"; case Modifier.STATIC : result = "static"; case Modifier.SYNCHRONIZED : result = "synchronized"; case Modifier.STRICT : result = "strict"; case Modifier.TRANSIENT : result = "transient"; case Modifier.VOLATILE : result = "volatile"; case Modifier.INTERFACE : result = "interface"; } return result; } public static void printClassDefinition(Class clz){ String clzModifier = getModifier(clz.getModifiers()); if(clzModifier!=null && !clzModifier.equals("")){ clzModifier = clzModifier + " "; } String superClz = clz.getSuperclass().getName(); if(superClz!=null && !superClz.equals("")){ superClz = "extends " + superClz; } Class[] interfaces = clz.getInterfaces(); String inters = ""; for(int i=0; i<interfaces.length; i++){ if(i==0){ inters += "implements "; } inters += interfaces[i].getName(); } System.out.println(clzModifier +clz.getName()+" " + superClz +" " + inters ); System.out.println("{"); Field[] fields = clz.getDeclaredFields(); for(int i=0; i<fields.length; i++){ String modifier = getModifier(fields[i].getModifiers()); if(modifier!=null && !modifier.equals("")){ modifier = modifier + " "; } String fieldName = fields[i].getName(); String fieldType = fields[i].getType().getName(); System.out.println(" "+modifier + fieldType + " "+ fieldName + ";"); } System.out.println(); Method[] methods = clz.getDeclaredMethods(); for(int i=0; i<methods.length; i++){ Method method = methods[i]; String modifier = getModifier(method.getModifiers()); if(modifier!=null && !modifier.equals("")){ modifier = modifier + " "; } String methodName = method.getName(); Class returnClz = method.getReturnType(); String retrunType = returnClz.getName(); Class[] clzs = method.getParameterTypes(); String paraList = "("; for(int j=0; j<clzs.length; j++){ paraList += clzs[j].getName(); if(j != clzs.length -1 ){ paraList += ", "; } } paraList += ")"; clzs = method.getExceptionTypes(); String exceptions = ""; for(int j=0; j<clzs.length; j++){ if(j==0){ exceptions += "throws "; } exceptions += clzs[j].getName(); if(j != clzs.length -1 ){ exceptions += ", "; } } exceptions += ";"; String methodPrototype = modifier +retrunType+" "+methodName+paraList+exceptions; System.out.println(" "+methodPrototype ); } System.out.println("}"); }
Rewrite the main method
##
public static void main(String[] args) { BusinessProcessorImpl bpimpl = new BusinessProcessorImpl(); BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl); BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(), bpimpl.getClass().getInterfaces(), handler); bp.processBusiness(); System.out.println(bp.getClass().getName()); Class clz = bp.getClass(); printClassDefinition(clz); }Now let’s take a look at the output:
You can do something here before process your business processing business..... You can do something here after process your business $Proxy0 $Proxy0 extends java.lang.reflect.Proxy implements com.tom.proxy.dynamic.BusinessProcessor { java.lang.reflect.Method m4; java.lang.reflect.Method m2; java.lang.reflect.Method m0; java.lang.reflect.Method m3; java.lang.reflect.Method m1; void processBusiness(); int hashCode(); boolean equals(java.lang.Object); java.lang.String toString(); }Obviously, the Proxy.newProxyInstance method will do the following things:
it's good now. Let’s see how the client adjusts it and it will become clear.
BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(....);2, bp.processBusiness();
Summary
The above is the detailed content of Detailed analysis of Proxy mechanism in Java. For more information, please follow other related articles on the PHP Chinese website!

NginxProxyManager配置解析与优化概述:NginxProxyManager是一个基于Nginx的反向代理管理工具,可以帮助我们方便地配置和管理反向代理服务器。在使用NginxProxyManager的过程中,我们可以通过对其配置进行解析与优化,提高服务器的性能与安全性。配置解析:配置文件位置和结构:NginxProxyManag

proxyprotocol在nginx中应用我们知道nginx是一个web服务器和代理服务器,它一般工作在proxyserver或者负载均衡软件(Haproxy,AmazonElasticLoadBalancer(ELB)的后面。客户端首先请求proxyserver或者LSB负载均衡软件,然后再到nginx进行真实的web访问。因为经过了多层软件,所以客户端的一些信息比如ip地址,端口号等可能就会被隐藏,这对于我们问题分析,数据统计都是不利的。因为对于nginx来说,我们希望能够获得真实的客户端

NginxProxyManager教程:快速入门指南,需要具体代码示例引言:随着网络技术的发展,代理服务器成为我们日常使用互联网的一部分。NginxProxyManager是一个基于Nginx的代理服务器管理平台,可以帮助我们快速建立和管理代理服务器。本篇文章将为大家介绍NginxProxyManager的快速入门指南,以及一些具体的代码示例。一

NginxProxyManager下的容器与微服务的部署策略,需要具体代码示例摘要:随着微服务架构的流行,容器化技术成为了现代软件开发的重要组成部分。而在微服务架构中,NginxProxyManager扮演着很重要的角色,用于管理和代理微服务的流量。本文将介绍如何使用NginxProxyManager来部署和管理容器化的微服务,并提供相关的代码示

如何使用NginxProxyManager实现多台服务器的负载均衡NginxProxyManager是一个基于Nginx开发的代理服务器管理工具,它提供了一个简单易用的Web界面,可以方便地配置和管理Nginx代理服务器。在实际应用中,我们经常需要将请求分发到多台服务器上,以实现负载均衡和提高系统的性能和可用性。本文将介绍如何使用NginxProx

NginxProxyManager是一个用于管理Nginx代理服务器的工具,通过使用它可以实现HTTP请求的缓存加速。下面将详细介绍如何使用NginxProxyManager实现缓存加速,并提供具体的代码示例。一、安装和配置NginxProxyManager安装NginxProxyManager:$npminstall-g@nginx

NginxProxyManager的日志分析与监控,需要具体代码示例引言:NginxProxyManager是一个基于Nginx的代理服务器管理工具,它提供了一种简单而有效的方法来管理和监控代理服务器。在实际运行中,我们常常需要对NginxProxyManager的日志进行分析和监控,以便及时发现潜在的问题或优化性能。本文将介绍如何使用一些常用的

NginxProxyManager原理与实践:优化网站性能的关键,需要具体代码示例引言:在当今互联网时代,网站性能对于用户体验和搜索引擎优化至关重要。为了提高网站的性能,一个有效的方法是使用Nginx作为反向代理服务器来管理和分发流量。本文将介绍NginxProxyManager的原理与实践,展示如何通过NginxProxyManager优化网站


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

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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