Dynamic agent and Nanning AOP
Keywords: AOP Nanning Dynamic Proxy AOP Dynamic Agent
Everyone knows that AOP programming has three ways:
1. Similar to Aspectj, inserting the code into the corresponding code using a specific syntax, typically compiling the completion of the Java class code implementation, interception and inferuct, etc.
2. Similar to JBossAop, use reflex mechanism to realize the function of AOP when loading;
3. Similar to Nanning (Nanning) uses Java dynamic agents.
The definition of the dynamic agent is as follows:
http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html
A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.
That is to say to use a dynamic agent, then a class behavior needs to implement a unified one or more interfaces to implement. When this instance is called, some interception can be performed.
For example, as follows:
Interface class:
Public interface foo {
Object bar (Object Obj) throws bazexception;
}
Implementation class:
Public Class FooImple Implements Foo {
Public Object Bar (Object Obj) throws bazexception {
Return Obj;
// ...
}
}
Dynamic Agent Class Implementation:
Import java.lang.reflect.InvocationTargeTexception;
Import java.lang.reflect.method;
Public class debugproxy imports java.lang.reflect.invocationhandler {
Private Object Obj;
Public static object newinstance (Object obj) {
Return java.lang.reflect.Proxy.NewProxyInstance (Obj.getClass ()
.getclassloader (), obj.getclass (). getInterfaces (),
New debugproxy (obj));
}
Private debugproxy (Object obj) {
this.obj = Obj;
}
Public Object Invoke (Object Proxy, M, Object [] ARGS
Throws throwable {
Object Result;
Try {
System.out.println ("Before Method" M.GetName ());
Result = m.invoke (OBJ, ARGS);
} catch (invocationTargeTexception E) {
throw E.GETTARGETEXCEPTION ();
} catch (exception e) {
Throw new runtimeException ("Unexpected Invocation Exception:" E.GetMessage ());
} finally {
System.out.println ("After Method" M.GetName ());
}
Return Result;
}
}
Test class:
Public class test {
Public static void main (string [] args) throws bazexception {
Foo foo = (foo) DebugProxy.NewInstance (New fooImple ());
FOO.BAR (NULL);
}
}
The operation is as follows:
BEFORE METHOD BAR
After Method Bar
It can be seen that when performing foo.bar (null);, the dynamic agent implements the interception after calling the method and the call.
Method intercepting interception is one of the features of AOP.
AOP implementation based on dynamic agents is generally the first choice for lightweight AOP FrameWrok, such as nanning and springframework.
Here are the implementation of Nanning AOP below.
Reference
http://www.9cbs.net/develop/Article/24/24445.shtm
Author: Tian Chunfeng
Column Address: http://www.9cbs.net/develop/author/netauthor/accesine960/