search
HomeJavajavaTutorialDetailed explanation of java proxy mode and dynamic proxy mode

1. Agency model

The so-called agency is a person or an organization taking action on behalf of another person or another organization. In some cases, a client does not want or cannot reference an object directly, and a proxy object can act as an intermediary between the client and the target object.
The proxy mode provides a proxy object for an object, and the proxy object controls the reference to the original object.

Example from real life: I am very busy working overtime during the Chinese New Year and have no time to buy train tickets. At this time, I can call the nearby ticketing center and ask them to buy a train ticket for me to go home. Of course, this will Additional labor charges apply. But it should be clear that the ticket center itself does not sell tickets. Only the train station actually sells tickets. The tickets the ticket center sells to you are actually realized through the train station. This is an important point!

In the above example, you are the "customer", the ticket center is the "agent role", the train station is the "real role", and selling tickets is called the "abstract role"!


Agent mode JAVA code example:
Abstract role: abstract class or interface

interface Business  
{  
    void doAction();  
}

Real role: truly implements the business logic interface

Agent role: I did not implement the business logic interface, but called the real role to implement

class BusinessImplProxy implements Business  
{  
    private BusinessImpl bi;  
    public void doAction()  
    {  
        if (bi==null)  
        {  
            bi = new BusinessImpl();  
        }  
        doBefore();  
        bi.doAction();  
        doAfter();  
    }  
    public void doBefore()  
    {  
        System.out.println("前置处理!");  
    }  
    public void doAfter()  
    {  
        System.out.println("后置处理!");  
    }  
}  
//测试类  
class Test  
{  
    public static void main(String[] args)  
    {  
        //引用变量定义为抽象角色类型  
        Business bi = new BusinessImplProxy();  
        bi.doAction();  
    }  
}
<span></span>

Therefore, with the support of JVM, the proxy class ("agent role") can be dynamically generated at runtime, and we can solve the above problem To solve the problem of code bloat in the proxy mode, after using dynamic proxy, the "agent role" will not be generated manually, but will be dynamically generated by the JVM at runtime by specifying three parameters: class loader, interface array, and call handler.

Dynamic proxy mode JAVA code example:

import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Proxy;
 import java.lang.reflect.Method;
 //抽象角色:java动态代理的实现目前只支持接口,不支持抽象类
 interface BusinessFoo
 {
     void foo();
 }
 interface BusinessBar
{
    String bar(String message);
}
//真实角色:真正实现业务逻辑方法
class BusinessFooImpl implements BusinessFoo
{
    public void foo()
    {
        System.out.println("BusinessFooImpl.foo()");
    }
}
class BusinessBarImpl implements BusinessBar
{
    public String bar(String message)
    {
        System.out.println("BusinessBarImpl.bar()");
        return message;
    }
}
//动态角色:动态生成代理类
class BusinessImplProxy implements InvocationHandler
{
    private Object obj;
    BusinessImplProxy() {
    }
    BusinessImplProxy(Object obj) {
        this.obj = obj;
    }
    public Object invoke(Object proxy,Method method,Object[] args) throws Throwable
    {
        Object result = null;
        doBefore();
        result = method.invoke(obj,args);
        doAfter();
        return result;
    }
    public void doBefore(){
        System.out.println("do something before Business Logic");
    }
    public void doAfter(){
        System.out.println("do something after Business Logic");
    }
    public static Object factory(Object obj)
    {
        Class cls = obj.getClass();
        return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new BusinessImplProxy(obj));
    }
}
//测试类
public class DynamicProxy
{    
    public static void main(String[] args) throws Throwable
    {
        BusinessFooImpl bfoo = new BusinessFooImpl();
        BusinessFoo bf = (BusinessFoo)BusinessImplProxy.factory(bfoo);
        bf.foo();
        System.out.println();

        BusinessBarImpl bbar = new BusinessBarImpl();
        BusinessBar bb = (BusinessBar)BusinessImplProxy.factory(bbar);
        String message = bb.bar("Hello,World");
        System.out.println(message);
    }
}

Program flow description:
new BusinessFooImpl(); Create a "real role" and pass it to the factory method BusinessImplProxy.factory(), and then Initialize the "invocation handler" - the class that implements InvocationHandler. And returns a dynamically created proxy class instance. Since the "agent role" must also implement the business logic methods provided by the "abstract role", it can be transformed down to BusinessBar and assigned to the reference bb pointing to the BusinessBar type.
newProxyInstance(ClassLoader loader, Class>[] interfaces, InvocationHandler h) method allows programmers to specify parameters and dynamically return the required proxy class, while the invoke(Object proxy, Method method, Object[] args) method It is dynamically called by the JVM at runtime. When executing the "bb.bar("Hello,World");" method, the JVM dynamically assigns an "invocation handler", passes parameters to the outer invoke, and calls method.invoke(obj, args) to actually execute it!

BusinessImplProxy.Factory static method is used to dynamically generate proxy classes ("agent roles"). According to different business logic interfaces BusinessFoo and BusinessBar, proxy roles are dynamically generated at runtime. "Abstract role", "agent role" and invocation handler (class that implements the InvocationHandler interface) can all be changed, so JAVA's dynamic proxy is very powerful.

For more detailed explanations of Java proxy mode and dynamic proxy mode, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function