A little idea about the dynamic agent of Java

Source: Internet
Author: User


Please correct me if there is any mistake.

1. The role of dynamic agents :

1. Dynamic proxy objects generated by virtual machines can easily be overridden by the original methods

2. If you do not have a dynamic proxy and want to implement overrides, you must do a subclass of the inherited base class



2. Example Demo:

Package com.didi.test;


Public interface Person {


String skill ();


String Play ();

}



Package com.didi.test;


public class Programmer implements person{



@Override

Public String skill () {

SYSTEM.OUT.PRINTLN ("Coding-------------------------");

Return "Call skill method";

}


@Override

Public String Play () {

return null;

}

}

Package com.didi.test;


Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Method;


public class Myinvocationhandler implements Invocationhandler {


Programmer Programmer;


Public Myinvocationhandler (Programmer Programmer) {

This.programmer = programmer;

}


@Override

public object invoke (object proxy, Method method, object[] args) throws Throwable {

System.out.println ("before------------");

System.out.println (Proxy.getclass (). GetName ());

Object obj = method.invoke (programmer);

System.out.println ("after----------------------");

if (!method.getname (). Equals ("skill")) {

Return "Call entertainment method";

}

return obj;

}

}

Package com.didi.test;


Import Java.lang.reflect.Proxy;


public class Proxtest {


public static void Main (string[] args) {

Programmer p = new Programmer ();

Person programmerproxy = (person) proxy.newproxyinstance (

ProxTest.class.getClassLoader (),

P.getclass (). Getinterfaces (),

New Myinvocationhandler (P));

System.out.println ("Parent class of the Dynamic proxy class:" + Programmerproxy.getclass (). Getsuperclass (). GetName ());

String mes = Programmerproxy.play ();

System.out.println (MES);

}

}

Console printing:

Parent class of the Dynamic proxy class: Java.lang.reflect.Proxy

Before------------

Com.sun.proxy. $Proxy 0

After----------------------

Call the Entertainment method


3. Underlying implementation principle


1. The following source code:

public static Object newproxyinstance (ClassLoader loader,

Class<?>[] interfaces,

Invocationhandler h)

Throws IllegalArgumentException

{

Objects.requirenonnull (h);


Final class<?>[] Intfs = Interfaces.clone ();

Final SecurityManager sm = System.getsecuritymanager ();

if (SM! = null) {

Checkproxyaccess (Reflection.getcallerclass (), loader, intfs);

}


/*

* Look up or generate the designated proxy class.

*/

class<?> cl = GETPROXYCLASS0 (loader, intfs);


/*

* Invoke its constructor with the designated invocation handler.

*/

try {

if (SM! = null) {

Checknewproxypermission (Reflection.getcallerclass (), CL);

}


Final constructor<?> cons = Cl.getconstructor (constructorparams);

Final Invocationhandler ih = h;

if (! Modifier.ispublic (Cl.getmodifiers ())) {

Accesscontroller.doprivileged (New privilegedaction<void> () {

Public Void Run () {

Cons.setaccessible (TRUE);

return null;

}

});

}

Return cons.newinstance (New object[]{h});

} catch (illegalaccessexception| Instantiationexception e) {

throw new Internalerror (E.tostring (), E);

} catch (InvocationTargetException e) {

Throwable t = e.getcause ();

if (t instanceof runtimeexception) {

throw (runtimeexception) t;

} else {

throw new Internalerror (t.tostring (), t);

}

} catch (Nosuchmethodexception e) {

throw new Internalerror (E.tostring (), E);

}

}


2. Source code Parsing

Proxy.newproxyinstance generates a proxy class object, this method does two important things, first generate the implementation class that implements the incoming interface, and then create the object by reflection, passing in a parameter when creating the object, that is, our own implementation of the Myinvocationhandler


3. Specific operating conditions

When you run the proxy object's method, the virtual machine does the following:

1. Collect three parameters: a reference to the proxy object, the method name of the currently calling method, the parameter of the method

2. Call the Invoke method of Myinvocationhandler, parameter for the parameters collected in the previous step


4. Practical Application

1. Log, transaction management

2. Remote procedure call RPC, when the remote call, the specific implementation on the server, then we implement communication in invoke (call method, let the remote method is called, the results can be played), all of this is through the socket in the invoke communication implementation

A wordy look:

Dynamic proxies make it easy to perform method enhancements, retrofits, and customizations to a class


A little idea about the dynamic agent of Java

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.