java-Dynamic Agent Technology

Source: Internet
Author: User

1. Agents in the program

For each method of the target class with the same interface, add some system functions, such as log, exception handling, calculation method running

Time, transaction management, and so on, can be handed to another class to implement these functions, which are called proxy classes.

Note: In order for the proxy class to share the various methods in the target class, you can have the proxy class implement the same interface as the target class.

 public  class   Aproxy { // aproxy class is a proxy class, You can calculate the run time of the Sayhi method  public  void  Span style= "color: #000000;"         > GetTime () { //  before method start time  new          A (). Sayhi ();      //  time after method end   class   a{ void   Sayhi () {System.out.println (" hi,everyone! "    ); }}

2. Proxy architecture diagram

It is managed in the same way as the Factory mode and configuration file , so there is no need to modify the client program to

The configuration file specifies whether to use the target class or the proxy class. This makes it easy to add/remove system functions.

When we need to test the performance of the system, we can use the proxy class, which can be used when the customer wants to use the target class

3.AOP (Aspect oriented program)

Cross-service: to handle different levels of business (service), called cross-service, such as security, transactions, logs, etc.

Security transaction Log
Studentservice------|----------|------------|-------------
Courseservice------|----------|------------|-------------
Miscservice------|----------|------------|-------------

Describe the cross-service with specific program code:
Method1 method2 method3
{                      {                       {
------------------------------------------------------Facets
....            ....              ......
------------------------------------------------------Facets
}                       }                       }

Aspect-oriented programming (AOP), the goal of AOP is to make the cross-service modular.

You can move the slice code around the original method, which is the same as if you were writing the slice code directly in the method, as follows:
------------------------------------------------------Facets
Func1 Func2 func3
{             {                {
....            ....              ......
}             }                }
      ------------------------------------------------------Section

Here is the use of proxy technology to solve this problem, the agent is the implementation of the AOP function of the core and key technology.
4. Dynamic Agent Technology

    • To add proxy functionality to the classes of various interfaces in the system, it will require too many proxy classes, all using static proxy mode, will be a very troublesome thing!
    • The JVM provides the dynamic proxy class (proxy). That is, the class's bytecode can be generated dynamically at run time , and this dynamically generated class is often used as a proxy class. This refers only to the proxy class and the target class with the interface.
    • For target classes without interfaces, the Cglib library can dynamically generate subclasses of a class, and subclasses of a class can also be used as proxies for that class, so if you want to generate a dynamic proxy class for a class that does not implement an interface, you can use the Cglib library.

The proxy method has the following four locations plus the system function code:

1. Before calling the target method
2. After calling the target method
3. Before and after calling the target method
4. In the catch block that handles the exception of the target method

class proxy{    void  SayHello () {        ... // 1        Try {            Target.sayhello ();        } Catch (Exception e) {            ... .. // 4         }        ... .... // 2     }}

5.Proxy (proxy Class)

|-java.lang.reflect.proxy

Proxy provides a static method for creating dynamic proxy classes and instances, which is also the super (parent) class of these created classes.

Construction Method:

Protected Proxy(Invocationhandler h);//Use the specified value of its invocation handler to build a new instance from a subclass (typically a dynamic proxy class) Proxy

Member Methods:

Static class<?> getproxyclass(ClassLoader loader,class<?> interfaces);//Create a dynamic proxy class with an interface.

Static Object newproxyinstance (ClassLoader loader,class<?>[] interfaces,invocationhandler h);// Returns a proxy class instance object

To create a proxy class and its instance objects:

Law One: Create the proxy class first, and then create the instance object with the constructor method of the proxy class

 Public Static voidMain (string[] args) {//gets a proxy class for the collection interface, specifying the interface and class loader for it//usually the loader,interface is the same as the bytecode producedClass Clazzproxy1=proxy.getproxyclass (Collection.class. getClassLoader (), Collection.class);        System.out.println (Clazzproxy1.getname ()); //Create a proxy class instance//Note: clazzproxy1.newinstance () calls its parameterless construction method to create an instance, but it does not have an argument-free construction method//create an instance by using a parametric constructor methodConstructor Ct=clazzproxy1.getconstructor (Invocationhandler.class); classMyinvocationhandlerImplementsInvocationhandler {@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {return NULL; }} Collection Proxy1= (Collection) ct.newinstance (NewMyinvocationhandler ()); }}

Method Two: Create a proxy class instance object directly with the new method

Object target=Newobject (); object Proxy1=proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (),NewInvocationhandler () {@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//TODO auto-generated Method Stubreturn NULL;}}); Class<?> []cs={collection.class}; Collection Proxy3=(Collection) proxy.newproxyinstance (Collection.class. getClassLoader (), CS,NewMyinvocationhandler ()); Collection Proxy4=(Collection) proxy.newproxyinstance (Collection.class. getClassLoader (),NewClass[] {Collection.class},         NewMyinvocationhandler ());

6.InvocationHandler (interface)

Member Methods:

Object invoke(Object proxy, Method method, Object[] args);// processes the method call on the proxy instance and returns the result.

In fact, when a proxy class object calls (The interface ) method, it actually calls the handler

The Invoke method. For a method that is not on the interface, such as GetClass (), it calls itself without delegating handler to invoke the Invoke method.

7. Mode of the proxy class

An object-oriented approach to the business of AOP (aspect-oriented programming), that is, when implementing the system functions of an agent, the target class object and interface (the interface is usually passed in a way that implements a class of interfaces, a class that implements a method (System function) in an interface) is passed as a parameter to a method that implements the system function.

ArrayList al=NewArrayList (); Collection Proxy4= (Collection) GetProxy (AL,NewMyadvice ()); Proxy4.add ("HQ"); //The following is a way to encapsulate the implementation of the proxy function//parameters: The target class object, and the interface (the class that implements the proxy function, the method that implements the function in the Class), which is usually passed in in a way that implements the interface of a class.     Private StaticObject GetProxy (FinalObject Target,FinalInterfaceadvice Advice) {Object Proxy=proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterf Aces (),NewInvocationhandler () {@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {Advice.beforemethod (method); Object obj=Method.invoke (target, args);                         Advice.aftermethod (method); returnobj;         }                }); returnproxy; }

8. Encapsulation and configuration of AOP functions

The factory class Beanfactory is responsible for creating an instance object of the target class or proxy class and switching through the configuration file. Its Getbean method returns an appropriate instance object based on the parameter string, if the parameter string in the configuration file corresponds to the class name is not Proxyfactorybean, then returns the instance object of the class directly, otherwise, returns the object returned by the GetProxy method of the class instance object.
The construction method of the beanfactory receives the input stream object representing the configuration file, with the following configuration file format:
#xxx =java.util.arraylist
Xxx=cn.itcast.proxyfactorybean
Xxx.target=java.util.arraylist
Xxx.advice=cn.itcast.myadvice
Proxyfacotrybean acts as a factory that encapsulates dynamic agents, what configuration parameter information is required for the factory class?
Goal: Target
Notice: Advice
To write a client application:
Writing classes that implement advice interfaces and configuring them in configuration files
Call Beanfactory to get an object

java-Dynamic Agent Technology

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.