Home > Java > javaTutorial > Detailed introduction to dynamic proxy mechanism in Java

Detailed introduction to dynamic proxy mechanism in Java

黄舟
Release: 2017-09-20 10:41:07
Original
1173 people have browsed it

This article mainly introduces the relevant information about the example explanation of the dynamic proxy mechanism in java. I hope that through this article everyone can understand and master the dynamic proxy mechanism. Friends in need can refer to the following

Dynamics in java Example explanation of 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, and For Spring's core AOP, we not only need to know how to satisfy our functions through AOP, but we also need to learn what its underlying principles are, and the principle of AOP is Java's dynamic proxy mechanism, so this article This essay is a review of Java's dynamic mechanism.

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 a method of the real object we want to call Method object

  • args: refers to the parameters accepted when calling a method of the real object

If you don’t understand it clearly , these parameters will be explained 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
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 proxy object, which receives three parameters, Let’s take a look at what these three parameters represent:

  • loader: A ClassLoader object that defines which ClassLoader object will load the generated proxy object

  • interfaces: An array of Interface objects, which represents a set of interfaces that I will provide to the object I need to proxy. If I provide a set of interfaces to it, then the proxy object will claim to implement it. This interface (polymorphic), so that I can call the methods in this set of interfaces

  • h: An InvocationHandler object, which represents when my dynamic proxy object is calling the method time, which InvocationHandler object will be associated

Okay, after introducing these two interfaces (classes), let’s take a look at our dynamic proxy mode through an example. What does it look 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

Then, 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 will define a dynamic proxy class, as shown above To put it bluntly, 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:


/**
 * Java学习交流QQ群:589809992 我们一起学Java!
 */
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? Woolen cloth?


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.

同时我们一定要记住,通过 Proxy.newProxyInstance 创建的代理对象是在jvm运行时动态生成的一个对象,它并不是我们的InvocationHandler类型,也不是我们定义的那组接口的类型,而是在运行是动态生成的一个对象,并且命名方式都是这样的形式,以$开头,proxy为中,最后一个数字表示对象的标号。

接着我们来看看这两句


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

这里是通过代理对象来调用实现的那种接口中的方法,这个时候程序就会跳转到由这个代理对象关联到的 handler 中的invoke方法去执行,而我们的这个 handler 对象又接受了一个 RealSubject类型的参数,表示我要代理的就是这个真实对象,所以此时就会调用 handler 中的invoke方法去执行:


/**
 * Java学习交流QQ群:589809992 我们一起学Java!
 */
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动态代理机制。

The above is the detailed content of Detailed introduction to 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