Java dynamic agents are only valid for implementation classes that implement interface methods, and the interface and implementation class codes are as follows:
Package Com.coshaho.reflect; Public Interface Subject { String dosomething ();}
Package Com.coshaho.reflect; Public class Implements subject{ @Override public String dosomething () { System.out.println ("Execute Service.") ); return "Done"; }}
Java Dynamic agent usage steps:
1, create dynamic Agent method processor (implement Invocationhandler interface);
PackageCom.coshaho.reflect;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;/*** Dynamic Proxy method Processor *@authorCoshaho **/ Public classProxyhandlerImplementsinvocationhandler{/*** Classes that need to be proxied*/ PrivateObject obj; Proxyhandler (Object obj) { This. obj =obj; } /*** Method: proxy class needs to be called methods * args: arguments passed in when the dynamic proxy class method is invoked * Proxy: Dynamic proxy class itself, generally useless*/@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Log:service Begin."); Object result=method.invoke (obj, args); System.out.println ("Log:service done."); returnresult; }}
Note: It is important to note that the dynamic proxy method processor instance generally needs to contain the proxy class (obj). The Invoke function is called when the dynamic proxy class is called an interface method, the argument is the dynamic proxy class itself, the proxy class needs to be called, and the dynamic proxy class invokes the parameters passed in the interface method.
2. Create a dynamic proxy class and use it.
PackageCom.coshaho.reflect;ImportJava.lang.reflect.Proxy; Public classDynamicproxy { Public Static voidMain (string[] args) {Subject Subject=NewRealsubject (); /*** proxy.newproxyinstance * Parameter 1: Dynamic proxy class required ClassLoader * Parameter 2: interface list implemented by Dynamic proxy class * Parameter 3: Dynamic proxy class Management Device*/Subject Proxysubject=(Subject) proxy.newproxyinstance (Subject.getclass (). getClassLoader (),NewClass[]{subject.class}, NewProxyhandler (subject)); Proxysubject.dosomething (); }}
Source analysis can be consulted: http://www.cnblogs.com/flyoung2008/archive/2013/08/11/3251148.html
Detailed description of dynamic agent in Java