Home >Java >javaTutorial >What is the principle and implementation method of Java dynamic proxy

What is the principle and implementation method of Java dynamic proxy

王林
王林forward
2023-05-20 17:52:061011browse

Agency refers to: In some scenarios, the subject will find an agent to assist him in completing some tasks, such as a celebrity's agent, a house buyer looking for a real estate agent, etc.

The agent mainly performs some additional auxiliary operations on the object's behavior.

How to create a proxy object:

The representative class of proxy in Java is: Java.lang.reflect.Proxy

Proxy provides a static method for generating objects for A proxy object returns

Main class:

public class Test {
    public static void main(String[] args) {
        //1、创建一个类,对象类必须实现接口
        star s=new star("小明");
        //为小明这个明星对象生成一个代理对象(经纪人)
        skill s2=StarAgentProxy.getProxy(s);
        s2.sing();//走代理的
        s2.jump();
        
        //运行结果:
        //代理开始
        //小明开始唱歌
        //代理结束
        //代理开始
        //小明开始跳舞
        //代理结束
    }
}

Star class (object class):

//明星类
public class star implements skill{
    private String name;
 
    public star(String name) {
        this.name = name;
    }
    //重写方法
    public void jump(){
        System.out.println(name+"开始跳舞");
    }
    public void sing(){
        System.out.println(name+"开始唱歌");
    }
}

Behavior interface class:

//行为类
public interface skill {
    void jump();//跳舞
    void sing();//唱歌
}

Proxy class:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
 
//代理类
public class StarAgentProxy {
    //定义一个方法来返回一个明星对象的代理对象
    public static skill getProxy(star obj){
        //为小明这个对象生成一个代理对象
        /*
          public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces, 对象实现的接口列表
                                          InvocationHandler h)
         */
        return (skill) Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("代理开始");
                        //真正的让小明去唱歌、跳舞
                        //method==>正在调用的方法对象, args==>代表这个方法的参数
                        Object rs=method.invoke(obj,args);
                        System.out.println("代理结束");
                        return rs;
                    }
                });
    }
}

Implementation steps:

1. The interface must exist

2. The proxy object needs to implement the interface

3. Use the method provided by the Proxy class to obtain the object The proxy object

What is the principle and implementation method of Java dynamic proxy

# calls a method through the proxy object. What is the execution process like?

1. Go to the agent first

2. The agent can do some additional auxiliary work for the method

3. Start the execution of the method that actually triggers the object

4. Back to the agent, the agent is responsible for returning the results to the caller of the method.

Key steps to optimize the code:

1. There must be an interface, and the implementation class must implement the interface (the agent is usually Based on interface implementation)

2. Create an object of the implementation class, which is a business object, and then make a proxy object for the business object

Advantages of dynamic proxy:

1. It can enhance the function of the method without changing the method source code, and improve the reuse of the code.

2. It simplifies the programming work, improves the development efficiency, and improves the software system. Scalability

3. Can be used as a proxy for all methods of the proxied object

4. It is very flexible and supports any implementation class object of any interface type as a proxy, or it can directly proxy the interface itself. Proxy

A framework for proxies for implementation class objects of any interface type (running generics)

    public static <T> T get(T obj){
        return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        return null;
                    }
                });
    }

The above is the detailed content of What is the principle and implementation method of Java dynamic proxy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete