Java Dynamic agent and old-fashioned AOP implementations

Source: Internet
Author: User
Tags throwable

Dynamic Agent for Java
Proxy mode is a common Java design pattern, his characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class, and the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but instead provides a specific service by invoking the related method of the object of the delegate class.
The proxy class can be divided into two types according to the agent's creation period.
The class file already exists.
Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism.

First look at the static proxy:
/**
* Define an Account interface
* @author Administrator
*/
Public interface Count {
//View account method br> public void Querycount ();
//Modify account Method
public void Updatecount ();
}


/**
* Delegate class (contains business logic)
*
* @author Administrator
*
*/
public class Countimpl Imp Lements Count {

@Override
public void Querycount () {
System.out.println ("View account Methods ...");
}

@Override
public void Updatecount () {
System.out.println ("Modify Account Method ...");
}
}


/**
* This is a proxy class (Enhanced Countimpl implementation Class)
*
* @author Administrator
*
*/
public class Countproxy I Mplements Count {
Private Countimpl Countimpl;

/**
* Overrides the default constructor
* @param countimpl
*/
Public countproxy (Countimpl Countimpl) { br> This.countimpl = Countimpl;
}

@Override
public void Querycount () {
System.out.println (before transaction processing);
//method of invoking the delegate class;
Countimpl.querycount ();
System.out.println (after transaction processing);
}

@Override
public void Updatecount () {
System.out.println (before transaction processing);
//method of invoking the delegate class;
Countimpl.updatecount ();
System.out.println (after transaction processing);
}

}


Import Net.battier.dao.impl.CountImpl;
Import Net.battier.dao.impl.CountProxy;
/**
* Test Count class
*
* @author Administrator
*
*/
public class Testcount {
public static void Main (string[] args) {
Countimpl Countimpl = new Countimpl ();
Countproxy countproxy = new Countproxy (COUNTIMPL);
Countproxy.updatecount ();
Countproxy.querycount ();
}
}

Observation code can find that each proxy class can only serve one interface, so that the development of the program will inevitably generate too many agents, and all the agent operation in addition to the method called, the other operations are the same, then it must be duplicated code. The best way to solve this problem is to complete the proxy function through a proxy class, which must be done using dynamic proxy.
Let's take a look at the dynamic proxy:

Schematic diagram:


The JDK dynamic agent contains a class and an interface:
Invocationhandler Interface:
Public interface Invocationhandler {
public object Invoke (Object Proxy,method method,object[] args) throws Throwable;
}
Parameter description:
Object proxy: Refers to the objects being proxied.
Method: Methods to invoke
object[] args: Parameters required for method invocation
The subclass of the Invocationhandler interface can be imagined as a proxy's final operation class, replacing the Proxysubject.
Proxy class:
The proxy class is an action class that specifically completes the proxy, which can be used to dynamically generate an implementation class for one or more interfaces, which provides the following operations:
public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) throws IllegalArgumentException
Parameter description:
ClassLoader Loader: Class loader
Class<?>[] Interfaces: Get all the interfaces
Invocationhandler h: Get subclass instance of Invocationhandler interface
Ps: Class Loader
In the proxy class in the Newproxyinstance () method requires an instance of the ClassLoader class, ClassLoader actually corresponds to the class loader, in Java, there are three kinds of loaders;
Booststrap ClassLoader: This loader is written in C + + and is not visible in general development;
Extendsion ClassLoader: Used to load the extension class, generally corresponding to the class in the Jre\lib\ext directory;
Appclassloader: (default) Loads the class specified by Classpath, which is most commonly used as an loader.
Dynamic Agent
The proxy class and the Invocationhandler interface in the Lang.reflect package provide the ability to generate dynamic proxy classes.
Dynamic Proxy Example:

Public interface Bookfacade {
public void Addbook ();
}

public class Bookfacadeimpl implements Bookfacade {

@Override
public void Addbook () {
System.out.println ("Add Book Method ... ");
}
}

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
/**
* JDK Dynamic Proxy proxy class
*
* @author Student
*
*/
public class Bookfacadeproxy implements Invocationhandler {
Private Object target;
/**
* Binds the delegate object and returns a proxy class
* @param target
* @return
*/
public object bind (object target) {
This.target = target;
Get proxy Object
Return Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), this); To bind the interface (this is a flaw, cglib compensates for this flaw) all class instantiation through this return, this action internally creates a class that implements all the interfaces of all incoming instance classes, creates a proxy entity from this class, and returns an instance of the class created by the dynamic proxy.
}

@Override
/**
* Call method
*/
public object invoke (object proxy, method, object[] args) throws Throwable {//This method implements AOP functionality and adds something after it has been executed
Object Result=null;
System.out.println ("things start");
Execution method
Result=method.invoke (target, args);
System.out.println ("End of Thing");
return result;
}

}

Import Net.battier.dao.BookFacade;
Import Net.battier.dao.impl.BookFacadeImpl;
Import Net.battier.proxy.BookFacadeProxy;
public class Testproxy {

public static void Main (string[] args) {
Bookfacadeproxy proxy = new Bookfacadeproxy ();
Bookfacade bookproxy = (bookfacade) proxy.bind (New Bookfacadeimpl ());
Bookproxy.addbook ();
}
}

However, the dynamic proxy of the JDK relies on the interface, and if some classes do not implement the interface, then the JDK proxy cannot be used, which will use the Cglib dynamic proxy.

Java Dynamic agent and old-fashioned AOP implementations

Related Article

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.