JDK1.2 provides a dynamic agent support, providing an execution processor by implementing a java.lang.reflect.InvocationHandler interface, then get a proxy object through java.lang.reflect.Proxy, through this proxy object to perform a business method, While the business method is called, the execution processor will be automatically called, thereby implementing the method interception. Nanning is the principle, and Spring has also used dynamic agents as one of the implementations.
Dynamic proxy definitions: 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.
Ginseng http://java.sun.com/j2se/1.4.2/docs/guide/reflection/proxy.html
This is a simple example:
interface:
Public interface foo {Object bar (Object obj) throws exception;}
A simple implementation:
Public Class FooImple Implements Foo {
Public Object Bar (Object Obj) throws exception {system.out.println ("Method Executing ..."); returnobj;}}
Agent class:
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, Method M, Object [] args throws throwable {
Object Result; try {//system.out.println proxy.getClass (). GetName ()); 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 exception {
Foo foo = (foo) DebugProxy.newinstance (New FooImple ()); foo.bar (New String ("Test");
}
}
Test Results:
D: y> java -classpath. TestBefore Method Barmethod Executing ... After Method Bar