java--Dynamic Agent Technology

Source: Internet
Author: User
Tags static class throwable

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 GetTime ()    {        //method before start time         New A (). Sayhi ();        Method End Time    }}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 void Main (string[] args) {        //Gets a proxy class for the collection interface, assigns it interface and ClassLoader        //usually Loader,interface is the same as the bytecode produced        Class  Clazzproxy1=proxy.getproxyclass (Collection.class.getClassLoader (), collection.class);        System.out.println (Clazzproxy1.getname ());        Create an instance of a proxy class        //Note: Clazzproxy1.newinstance () invokes its parameterless construction method to create an instance, but it does not have a parameterless construction method//        creates an instance by means of a parametric constructor        Constructor Ct=clazzproxy1.getconstructor (invocationhandler.class);        Class Myinvocationhandler implements Invocationhandler        {             @Override public            object Invoke (object proxy, Method method, object[] args)                    throws Throwable {                 return null;            }         }        Collection proxy1= (Collection) ct.newinstance (New Myinvocationhandler ());}     }

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

Object Target=new Object (), Object Proxy1=proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), new Invocationhandler () {@Overridepublic object Invoke (Object proxy, method, Object[] args) throws Throwable {//TODO auto-generated method Stubreturn null;}}); class<?> []cs={collection.class}; Collection proxy3= (Collection) proxy.newproxyinstance        (Collection.class.getClassLoader (),          cs,new Myinvocationhandler ()); Collection proxy4= (Collection) proxy.newproxyinstance        (Collection.class.getClassLoader (),         new class[] { Collection.class},         new Myinvocationhandler ());

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=new ArrayList ();        Collection proxy4= (Collection) getproxy (al,new myadvice ());        Proxy4.add ("HQ");    The following is a method//parameter that encapsulates the implementation of the proxy function    : 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 static Object GetProxy (Final object target,final interfaceadvice advice) {         object proxy= Proxy.newproxyinstance                (Target.getclass (). getClassLoader (),                 Target.getclass (). Getinterfaces (),                 new Invocationhandler () {                                        @Override public                    object Invoke (Object proxy, Method method,                            object[] args) throws Throwable {                         Advice.beforemethod (method);                         Object Obj=method.invoke (target, args);                         Advice.aftermethod (method);                         return obj;                    }                });         return proxy;    }

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 the object.

From

Http://www.cnblogs.com/beyondbycyx/p/4314536.html

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.