Java Dynamic Agent

Source: Internet
Author: User

Learn about dynamic proxies for Java.

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 our dynamic proxy. First, let's take a look at how the Java API Help document describes these two classes:

Description of Invocationhandler:

InvocationHandleris the interface implemented by theInvocation Handlerof a proxy instance.

Each proxy instance have an associated invocation handler. When a method was invoked on a proxy instance, the method invocation was encoded and dispatched to the invoke method of its I Nvocation handler.

Invocationhandler is the interface that is implemented by the calling handler for the proxy instance. Each proxy instance has an associated call handler. When a method is called on the proxy instance, the method call is assigned to the Invoke method that invokes the handler.

It has the only way:

  

object Invoke (object proxy,              method method,              object[] args)       throws Throwable

Action: Processes the method Call of the proxy instance and returns the result

Description of Proxy:

ProxyProvides static methods for creating dynamic proxy classes and instances, and it's also the superclass of all dynamic Pro XY classes created by those methods.

The proxy provides a static method for creating dynamic proxy classes and instances, or a superclass of all dynamic proxy classes created by these methods.

It has one method:

Static Object    newproxyinstance (ClassLoader loader, class<?>Class for the specified Interfaces that dispatches method invocations to the specified invocation handler.

Function: Returns an instance of a proxy class that specifies an interface method call that is assigned to the specified invocation handler.

Below we coded the test:

1. We define an interface foo

 Public Interface Foo {    publicvoid  SayHello ();      Public void Saygoodbye (String name);}

2 interface methods are defined in the interface, SayHello and Saygoodbye with parameters.

2. Define an implementation class for the Foo interface Fooimpl

 Public class Implements Foo {    @Override    publicvoid  SayHello () {        System.out.println ("Hello World ");    @Override    publicvoid  Saygoodbye (String name) {        SYSTEM.OUT.PRINTLN (name + ", goodbye!" );    }}

3. Define a Invocationhandler implementation class Myinvocationhandler

 Public classMyinvocationhandlerImplementsInvocationhandler {//This is the real object we're going to be acting for.    PrivateObject MyObject; //Assigning a value to a real object     PublicMyinvocationhandler (Object myObject) { This. MyObject =MyObject; } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//we can add some of our own actions before acting on the real object.System.out.println ("Action before calling method"); //Real Object Invocation methodsMethod.invoke (Myobject,args); //we can add some of our own actions after acting on the real object.SYSTEM.OUT.PRINTLN ("Action after calling method"); return NULL; }}

4. Verification

 Public classClient { Public Static voidMain (string[] args) {//the real object we're going to be acting forFooimpl Fooimpl =NewFooimpl (); Invocationhandler Handler=NewMyinvocationhandler (Fooimpl); //Get proxy ObjectFoo f = (foo) proxy.newproxyinstance (foo).class. getClassLoader (),NewClass<?>[]{foo.class}, handler);        System.out.println (F.getclass (). GetName ());        F.sayhello (); F.saygoodbye ("Bokeyuan"); }}

The console output is:

Sun.proxy. $Proxy 0 operation before calling method Hello World Call method operation Bokeyuan before action called method, goodbye! operation after calling method

We found that the class name of the proxy object is $proxy0, which is generated automatically by the JVM. When invoking a method through a proxy object, it is actually called by the Invoke method of the handler object to which the delegate is associated, not by itself, but by proxy. In the Invoke method, we can extend the functionality of the class.

  

Reference documents

http://docs.oracle.com/javase/8/docs/api/?cm_mc_uid=68572479042314694146274&cm_mc_sid_50200000=1469666414

A detailed description of the dynamic agent mechanism in Java, http://www.importnew.com/20732.html

Java Dynamic Agent

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.