Analysis of dynamic agent mechanism in Java

Source: Internet
Author: User
Tags object object throwable

1. Overview
First, let's consider the following two questions:
What is proxy mode? Why use proxy mode?

To summarize briefly, the so-called proxy model is to add a placeholder to the original service to control access to the service through this placeholder. With proxy mode, you can control how to access real service objects and provide additional services, and on the other hand, have the opportunity to rewrite some classes to meet specific needs.

In the dynamic agent mechanism of Java, there are two important classes or interfaces, one is Invocationhandler (Interface), the other is proxy (class), and this class and interface is necessary to implement dynamic proxy. Let's look at the following specific analysis:
(1) Invocationhandler interface: When a method is called through a proxy object, the invocation of this method is forwarded to the Invoke method of the Invocationhandler interface. The Invocationhanler invoke method is as follows:
Object Invoke (Object proxy, Method method, object[] args) throws Throwable
The specific meanings of the three parameters are as follows:
Proxy: The real object of the agent
Method: Methods object that invokes the real object
Args: Parameters received when invoking a method of a real object

(2) proxy class: The function of this class is to dynamically create a proxy object class, it provides a lot of methods, but we use the most is newproxyinstance this method, as follows:
public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) throws IllegalArgumentException

The function of this method is to get a dynamic proxy object, which receives three parameters, and we take a look at what these three parameters mean:

Loader: A ClassLoader object that defines which ClassLoader object to load on the generated proxy object;
Interfaces: An array of interface objects, which means that I'm going to provide a set of interfaces to the object I need to proxy, and if I provide a set of interfaces to it, then this proxy object declares the implementation of the interface (polymorphic) so that I can invoke the methods in this set of interfaces;
H: A Invocationhandler object that represents the Invocationhandler object to which the dynamic proxy object is associated when it invokes the method.

2. Example

(1) We first define an interface:

Public interface Library {    void Isavalid ();    void SayHello (String name);}

(2) The implementation class of the interface:

public class Book implements Library {    @Override public    void Isavalid () {        System.out.println ("The book can B E borrowed! ");    }    @Override public    void SayHello (String name) {        System.out.println ("Book Name is:" + name);}    }

(3) Dynamic agent:

public class Dynamicproxy implements Invocationhandler {    Private object object;    Public Dynamicproxy (Object object) {        This.object = object;    }    @Override Public    object Invoke (Object proxy, Method method, object[] args) throws Throwable {        System.out.println ("Bollow flow begin ...");        System.out.println ("Method name is:" + method);        Method.invoke (object, args);        System.out.println ("Bollow flow End ...");        return null;}    }

(4) Test class:

public class Reader {public    static void Main (string[] args) {book Book        = new book ();        Invocationhandler handler = new Dynamicproxy (book);        Library library = (library) proxy.newproxyinstance (Handler.getclass (). getClassLoader (),                Book.getclass (). Getinterfaces (), handler);        System.out.println (Library.getclass (). GetName ());        Library.isavalid ();        Library.sayhello ("<java Concurrency in Practice>");}    } Result output: $Proxy 0Bollow flow begin ... Method name Is:public abstract void Com.cn.dynamicProxy.Library.isAvalid () This book can be borrowed! Bollow Flow End ... Bollow Flow begin ... Method name Is:public abstract void Com.cn.dynamicProxy.Library.sayHello (java.lang.String) book name is: <java Concurrency in Practice>bollow flow end ...

Description

The proxy object created through Proxy.newproxyinstance is an object that is dynamically generated at runtime by the JVM, not our invocationhandler type, nor the type of the set of interfaces we define, but an object that is dynamically generated when it is run. And the naming method is in this form, starting with $, proxy is medium, and the last number represents the label of the object.

The actual operating method:
Method name Is:public abstract void Com.cn.dynamicProxy.Library.isAvalid ()
Method name Is:public abstract void Com.cn.dynamicProxy.Library.sayHello (java.lang.String)
So, when I invoke a method through a proxy object, it is actually called by the Invoke method of the handler object to which it is associated, not by the actual invocation, but by proxy. This is the dynamic proxy mechanism for Java.

Analysis of dynamic agent mechanism in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.