Home > Java > javaTutorial > Detailed analysis of dynamic proxy mechanism in Java

Detailed analysis of dynamic proxy mechanism in Java

黄舟
Release: 2017-09-08 09:46:50
Original
1271 people have browsed it

This article mainly introduces relevant information about the detailed examples of Java dynamic proxy mechanism. I hope that through this article, everyone can master the dynamic proxy mechanism. Friends in need can refer to

Java Dynamic Proxy Mechanism

When learning spring, we know that Spring mainly has two major ideas, one is IoC and the other is AOP. For IoC, it goes without saying much about dependency injection, but for Spring’s core AOP That is to say, we not only need to know how to satisfy our functions through AOP, but we also need to learn the underlying principle. The principle of AOP is Java's dynamic proxy mechanism, so this essay is an introduction to Java. A review of dynamic mechanisms.

In the dynamic proxy mechanism of java, there are two important classes or interfaces, one is InvocationHandler (Interface) and the other is Proxy (Class). This class and interface are used to implement our dynamic proxy. Must be used. First, let’s take a look at how the Java API help document describes these two classes:

InvocationHandler:


InvocationHandler is the interface implemented by the invocation handler of a proxy instance. 
Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.
Copy after login

Each dynamic The proxy class must implement the InvocationHandler interface, and each proxy class instance is associated with a handler. When we call a method through the proxy object, the call of this method will be forwarded to the invoke method of the InvocationHandler interface. to make the call. Let's take a look at the only method of the InvocationHandler interface, the invoke method:


Object invoke(Object proxy, Method method, Object[] args) throws Throwable
Copy after login

We see that this method accepts a total of three parameters, so what do these three parameters represent? ?

proxy: refers to the real object we are proxying
method: refers to the Method object that we want to call a method of the real object
args: refers to the method of calling the real object If you don’t understand the parameters accepted by a certain method

, I will explain these parameters in depth through an example later.

Next let’s take a look at the Proxy class:


Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
Copy after login

The function of the Proxy class is to dynamically create a proxy object. It provides There are many methods, but the one we use most is the newProxyInstance method:


public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, 
 InvocationHandler h) throws IllegalArgumentException
Copy after login


Returns an instance of a proxy class for the specified interfaces that dispatches method
 invocations to the specified invocation handler.
Copy after login

The function of this method is to get a dynamic The proxy object receives three parameters. Let’s take a look at the meaning of these three parameters:


loader:一个ClassLoader对象,定义了由哪个ClassLoader对象来对生成的代理对象进行加载
interfaces:一个Interface对象的数组,表示的是我将要给我需要代理的对象提供一组什么接口,如果我提供了一组接口给它,那么这个代理对象就宣称实现了该接口(多态),这样我就能调用这组接口中的方法了
h:一个InvocationHandler对象,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上
Copy after login

Okay, after introducing these two interfaces ( class), let’s take an example to see what our dynamic proxy mode looks like:

First we define an interface of Subject type and declare two methods for it:


public interface Subject
{
  public void rent();

  public void hello(String str);
}
Copy after login

Next, a class is defined to implement this interface. This class is our real object, RealSubject class:


public class RealSubject implements Subject
{
  @Override
  public void rent()
  {
    System.out.println("I want to rent my house");
  }

  @Override
  public void hello(String str)
  {
    System.out.println("hello: " + str);
  }
}
Copy after login

Next, we have to define a dynamic proxy class. As mentioned earlier, every dynamic proxy class must implement the InvocationHandler interface, so our dynamic proxy class is no exception:


public class DynamicProxy implements InvocationHandler
{
  // 这个就是我们要代理的真实对象
  private Object subject;

  //  构造方法,给我们要代理的真实对象赋初值
  public DynamicProxy(Object subject)
  {
    this.subject = subject;
  }

  @Override
  public Object invoke(Object object, Method method, Object[] args)
      throws Throwable
  {
    //  在代理真实对象前我们可以添加一些自己的操作
    System.out.println("before rent house");

    System.out.println("Method:" + method);

    //  当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用
    method.invoke(subject, args);

    //  在代理真实对象后我们也可以添加一些自己的操作
    System.out.println("after rent house");

    return null;
  }

}
Copy after login

Finally, let’s take a look at our Client class:


public class Client
{
  public static void main(String[] args)
  {
    //  我们要代理的真实对象
    Subject realSubject = new RealSubject();

    //  我们要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法的
    InvocationHandler handler = new DynamicProxy(realSubject);

    /*
     * 通过Proxy的newProxyInstance方法来创建我们的代理对象,我们来看看其三个参数
     * 第一个参数 handler.getClass().getClassLoader() ,我们这里使用handler这个类的ClassLoader对象来加载我们的代理对象
     * 第二个参数realSubject.getClass().getInterfaces(),我们这里为代理对象提供的接口是真实对象所实行的接口,表示我要代理的是该真实对象,这样我就能调用这组接口中的方法了
     * 第三个参数handler, 我们这里将这个代理对象关联到了上方的 InvocationHandler 这个对象上
     */
    Subject subject = (Subject)Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject
        .getClass().getInterfaces(), handler);

    System.out.println(subject.getClass().getName());
    subject.rent();
    subject.hello("world");
  }
}
Copy after login

Let’s first take a look at the console output:


$Proxy0

before rent house
Method:public abstract void com.xiaoluo.dynamicproxy.Subject.rent()
I want to rent my house
after rent house

before rent house
Method:public abstract void com.xiaoluo.dynamicproxy.Subject.hello(java.lang.String)
hello: world
after rent house
Copy after login

Let’s first take a look at $Proxy0. We see that this thing is printed by the statement System.out.println(subject.getClass().getName()); So why is the class name of the proxy object we return like this?


Subject subject = (Subject)Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject
        .getClass().getInterfaces(), handler);
Copy after login

Maybe I thought that the returned proxy object would be a Subject type object, or an InvocationHandler object, but it turned out not to be the case. First, let’s explain why we can use Convert it to an object of type Subject? The reason is that in the second parameter of the newProxyInstance method, we provide a set of interfaces for this proxy object, then my proxy object will implement this set of interfaces. At this time, of course we can force the type conversion of this proxy object. It is any one of this set of interfaces. Because the interface here is of Subject type, it can be converted into Subject type.

At the same time, we must remember that the proxy object created through Proxy.newProxyInstance is an object dynamically generated when the jvm is running. It is not our InvocationHandler type, nor is it the type of the set of interfaces we defined. , but an object that is dynamically generated at runtime, and the naming method is in this form, starting with $, proxy is in the middle, and the last number represents the label of the object.

Then let’s take a look at these two sentences


subject.rent();
subject.hello(“world”);
Copy after login

Here are the methods in the interface that are implemented through proxy objects. At this time, the program Will jump to the invoke method in the handler associated with this proxy object for execution, and our handler object accepts a RealSubject type parameter, which means that the real object I want to proxy is the real object, so it will be called at this time The invoke method in the handler is executed:


public Object invoke(Object object, Method method, Object[] args)
      throws Throwable
  {
    //  在代理真实对象前我们可以添加一些自己的操作
    System.out.println("before rent house");

    System.out.println("Method:" + method);

    //  当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用
    method.invoke(subject, args);

    //  在代理真实对象后我们也可以添加一些自己的操作
    System.out.println("after rent house");

    return null;
  }
Copy after login

我们看到,在真正通过代理对象来调用真实对象的方法的时候,我们可以在该方法前后添加自己的一些操作,同时我们看到我们的这个 method 对象是这样的:


public abstract void com.xiaoluo.dynamicproxy.Subject.rent()

public abstract void com.xiaoluo.dynamicproxy.Subject.hello(java.lang.String)
Copy after login

正好就是我们的Subject接口中的两个方法,这也就证明了当我通过代理对象来调用方法的时候,起实际就是委托由其关联到的 handler 对象的invoke方法中来调用,并不是自己来真实调用,而是通过代理的方式来调用的。

这就是我们的java动态代理机制。

本篇随笔详细的讲解了java中的动态代理机制,这个知识点非常非常的重要,包括我们Spring的AOP其就是通过动态代理的机制实现的,所以我们必须要好好的理解动态代理的机制。

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template