Dynamic agent of Java learning

Source: Internet
Author: User

Why a dynamic proxy is used by a Java dynamic agent

When a method of a class needs to be decorated (enhanced), you can use inheritance, decorator mode, and dynamic proxy.

Three ways of limiting:

    1. Inheritance: Enhanced objects cannot be changed, and enhanced content cannot be changed.
    2. Decorator mode: The enhanced object cannot be changed and the enhanced content can be changed.
    3. Dynamic proxies: Enhanced objects can be changed, and enhanced content can be changed.

Using dynamic proxies gives you more flexibility in increasing the reusability of your code.

Give me a chestnut:
For computer teachers This class, there is a teach () method, the past, the old teaching mode may not be suitable for the rapid development of the computer industry, so in the use of this teach () method may need to add something in front or behind. But for older projects, it's hard to understand the way they are written and thought, so we can't easily modify their code, so we can use proxies to implement enhancements to the Teach () method (I'm divided into pre-and post-enhancement).

How to use Dynamic proxy object Proxy.newinstance (ClassLoader loader, class[] interfaces, Invocationhandler IH)
    1. Loader: Class loader, loading classes into memory.
    2. Interfaces: The interface to be implemented by the proxy object.
    3. Ih:invocationhandler, which implements the Invoke () method, to implement enhancements to the target object.
    4. Return value: An object generated dynamically by the JVM runtime, which is not our invocationhandler type, nor the type of the set of interfaces we define, but rather a dynamically generated object that runs
Invocationhandler interface

The interface needs to implement the Invoke () method.

Object Invoke (Object proxy, Method method, object[] args)
    1. Proxy: Agent object.
    2. Method: The target approach used by the proxy object.
    3. Args: The parameters of the target method.
    4. Return value: The return value of the methods method.

When using a method with a proxy object, the Invoke () method of the Invocationhandler that is passed in when the proxy object is generated is called, so you can write content that needs to be enhanced in this invoke ().

Demo

First, give two interfaces and an implementation class

publicinterface Subject {    publicintoutPut(int num);}
public   bsubject {public  int  output2  (int  num);}  
public  class  Realsubject implements  Subject, Bsubject { @Override  public  int  
    
     output  (
     int  num) {system.
     . println  ( "OutPut"  + String. valueof         (num) +  "people" );    return  num; }  @Override  public  int   (int  num) {system.. println  ( "OutPut2"  + String. valueof  (num) +  "people" ); return  num; }}
    

Using dynamic proxies

Front-mounted Enhancement interface:

publicinterface// 前置增强接口    publicvoidbefore();}

Post-enhanced Interface:

publicinterface// 后置增强接口    publicvoidafter();}

Creating a proxy factory makes it easier to invoke:

import Java.lang.reflect.InvocationHandler;import Java.lang.reflect.Method;import Java.lang.reflect.Proxy; Public classproxyfactory {PrivateObject TargetObject;//Target Agent object    PrivateBeforeadvance beforeadvance;//front-mounted enhancements    PrivateAfteradvance afteradvance;//rear-mounted enhancements     PublicObjectcreatefactory() {ClassLoader loader = This.GetClass().getClassLoader();//load. class to MemoryClass[] interfaces = TargetObject.GetClass().getinterfaces();///Get Realsubject all Interfaces (waiter), provide a set of interfaces to the proxy object, this proxy object will implement this set of interfaces,Invocationhandler ih =NewInvocationhandler () {@Override            /Proxy is a proxy object, a dynamically generated object at the runtime of the JVM, it is not our invocationhandler type, nor is it the type of the set of interfaces we define, but rather a dynamically generated object that runs            //method is the way the target object needs to be enhanced            //args is an argument             PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsThrowable {if(Beforeadvance! =NULL) {//Call forward enhancement methodBeforeadvance.before(); } Object result = method.Invoke(TargetObject, args);//Call the target method of the target proxy object by reflection, result is the return value of the target method                if(Afteradvance! =NULL) {//Call the post-enhancement methodAfteradvance. After(); }returnResult }        };returnProxy.newproxyinstance(loader, interfaces, IH);//Get a proxy object} PublicAfteradvancegetafteradvance() {returnAfteradvance; } Public void setafteradvance(Afteradvance afteradvance) { This.afteradvance= Afteradvance; } PublicBeforeadvancegetbeforeadvance() {returnBeforeadvance; } Public void setbeforeadvance(Beforeadvance beforeadvance) { This.beforeadvance= Beforeadvance; } PublicObjectGettargetobject() {returnTargetObject; } Public void Settargetobject(Object TargetObject) { This.TargetObject= TargetObject; }}

Example:

import org.junit.Test; Public classDemo {@Test     Public void  Fun() {Proxyfactory proxyfactory =New proxyfactory();//target object for the agentProxyfactory.Settargetobject(New Realsubject());//Pre-enhanced interface implementationProxyfactory.setbeforeadvance(New beforeadvance() {@Override             Public void before() {System. out.println("Hello"); }        });//rear-mounted enhanced interface implementationProxyfactory.setafteradvance(New afteradvance() {@Override             Public void  After() {System. out.println("Byebye"); }        });//Generate an implementation class object for the subject interfaceSubject Subject = (Subject) proxyfactory.createfactory();//through newinstance () to get a proxy object, this proxy object implements the subject interface, so it can be strongly converted to subject interface class. Bsubject Subject2 = (bsubject) proxyfactory.createfactory(); Object result = subject.OutPut( -);//corresponding to the Invocationhandler invoke method: Subject as proxy, output as method, parameter argsSystem. out.println(result); System. out.println("-----"); Object result2 = Subject2.OutPut2( -); System. out.println(RESULT2); }} Output: Hellooutput -Peoplebyebye ------HELLOOUTPUT2 -Peoplebyebye -

In this case, as long as the use of reflection, Method.invoke () can invoke the proxy target object of the method, and then implement the pre-enhanced Beforeadvance interface and the post-enhanced Afteradvance interface, you can implement the method to enhance the content.
Beforeadvance and afteradvance can be reused by different implementations of different interfaces.
For different enhancement objects can also be used, as long as the targetobject to change a bit.

Attach a good article to the story

Dynamic agent of Java learning

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.