search
HomeJavajavaTutorialExample analysis of dynamic proxy and static proxy in Java

    0. Agent mode

    Why should we learn the agent mode? This is the bottom layer of SpringAOP [SpringAOP and SpringMVC]

    Classification of proxy mode:

    • Static proxy

    • Dynamic proxy

    1. Static proxy

    In static proxy, our enhancement of each method of the target object is done manually ( The code will be demonstrated in detail later_), very inflexible (for example, once a new method is added to the interface, the target object and proxy object must be modified) and troublesome (_need to write a separate proxy class for each target class). There are very few actual application scenarios, and there are almost no scenarios where static proxies are used in daily development.

    Role analysis:

    • Abstract role: Generally, interfaces or abstract classes are used to solve the problem

    • Real role: Acted role

    • Agent role: Act as the real role. After acting as the real role, we usually do some subsidiary operations

    • Customer: The person who accesses the proxy object!

    Code steps:

    1. Interface

    public interface Rent {
        public void rent();
    }

    2. Real character

    //房东
    public class Host implements Rent {
        public void rent() {
            System.out.println("房东要租房子");
        }
    }

    3. Agent role

    public class Proxy implements Rent{
        private Host host;
        public Proxy() {
        }
        public Proxy(Host host) {
            this.host = host;
        }
        public void rent(){
            seeHouse();
            host.rent();
            fare();
        }
        //看房
        public void seeHouse(){
            System.out.println("中介带你看房");
        }
        //收中介费
        public void fare(){
            System.out.println("中介收费");
        }
    }

    4. Client access to the agent role

    public class Client {
        public static void main(String[] args) {
            Host host = new Host();
            //代理,代理角色一般会有附属操作!
            Proxy proxy = new Proxy(host);
            proxy.rent();
        }
    }

    Benefits of the agent mode:

    • can make real roles The operation is more pure! There is no need to pay attention to some public business

    • The public will be left to the agent role! Realize the division of labor in business!

    • When public services expand, centralized management is convenient!

    Disadvantages:

    A real role will generate a proxy role; from a JVM perspective, a static proxy changes the interface, Implementation classes and proxy classes have become actual class files.

    2. Deepen understanding of

    AOP, the underlying proxy model

    Example analysis of dynamic proxy and static proxy in Java

    3. Dynamic proxy

    • The role of dynamic proxy is the same as that of static proxy

    • The proxy class of dynamic proxy is dynamically generated, not written directly by us!

    • Dynamic agents are divided into two categories: interface-based dynamic agents and class-based dynamic agents

      • Interface-based— —JDK dynamic proxy

      • Based on class: cglib dynamic proxy

      • java bytecode implementation: javasist

    You need to understand two classes: Proxy: proxy class, InvocationHandler: call handler

    From the JVM perspective, dynamic proxy dynamically generates class bytecode at runtime , and loaded into the JVM.

    //Proxy是生成动态代理类,提供了创建动态代理类和实例的静态方法,它也是由这些方法创建的所有动态代理类的超类。
    //InvocationHandler-- invoke 调用处理程序并返回接口, 是由代理实例的调用处理程序实现的接口 。

    Benefits of dynamic proxy:

    • can make the operation of real characters more pure! There is no need to deal with some public business

    • The public will be left to the agent role! Implementation

    public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h){
    }

    1.loader : Class loader, used to load proxy objects.

    2.interfaces : Some interfaces implemented by the proxy class;

    3.h : An object that implements the InvocationHandler interface;

    To implement a dynamic proxy, you must also implement InvocationHandler to customize the processing logic. When our dynamic proxy object calls a method, the call to this method will be forwarded to the invoke method of the class that implements the InvocationHandler interface.

    public interface InvocationHandler {
        Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
    }

    1.proxy: dynamically generated proxy class

    2.method: corresponds to the method called by the proxy class object

    3.args: Parameters of the current method method

    Example of dynamic proxy

    1. Define the interface

    public interface Rent {
        public void rent();
    }

    2. Implement rental Interface

    public class Host implements Rent {
        @Override
        public void rent() {
            System.out.println("房东要租房");
        }
    }

    3. Define a JDK dynamic proxy class

    public class DebugInvocationHandler implements InvocationHandler {
        /**
         * 代理类中的真实对象
         */
        private final Object target;
        public DebugInvocationHandler(Object target){
            this.target = target;
        }
        /**
         * 当你使用代理对象调用方法的时候实际会调用到这个方法
         */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //调用方法前
            System.out.println("before method" + method.getName());
            Object res = method.invoke(target, args);
            //调用方法后
            System.out.println("after method" + method.getName());
            return res;
        }
    }

    invoke() Method: When our dynamic proxy object calls the native method, it will actually be called What we get is the invoke() method, and then the invoke() method calls the native method of the proxy object on our behalf.

    4. Get the factory class of the proxy object

    public class JdkProxyFactory {
        public static Object getProxy(Object target){
            return Proxy.newProxyInstance(
                    target.getClass().getClassLoader(),
                    target.getClass().getInterfaces(),
                    new DebugInvocationHandler(target)
            );
        }
    }

    getProxy(): Mainly obtain the factory class of a certain class through the Proxy.newProxyInstance() method Proxy object

    5. Actual use

    public static void main(String[] args) {
            //Rent rent = new Host();
            //Rent rentProxy= (Rent) Proxy.newProxyInstance(rent.getClass().getClassLoader(), rent.getClass().getInterfaces(),new DebugInvocationHandler(rent));
            Rent rentProxy = (Rent)JdkProxyFactory.getProxy(new Host());
            rentProxy.rent();
        }

    The output of running the above agent

    before methodrent
    The landlord wants to rent a house
    after methodrent

    The above is the detailed content of Example analysis of dynamic proxy and static proxy in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

    JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

    Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

    JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

    JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

    TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

    JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

    JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

    Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

    Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

    Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

    JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

    What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

    Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

    Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

    The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

    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 Article

    Hot Tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    mPDF

    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),