A dynamic agent can only broker an interface and cannot proxy a class.
Dynamic proxies include aspect-oriented programming, which allows you to manipulate legacy code without manipulating the original code.
Dynamic Agent Implementation steps: Create a proxy class to implement the Java.lang.reflect.InvocationHandler interface, create the target object, the object that needs the proxy, complete the Proxy.newproxyinstance () method, The three parameters passed in are difficult I think the first is the loader of the target object (the loader of the interface), the second parameter class, and the third parameter is the Invocationhandler object.
There are two ways to write a proxy class, but the idea is the same, write one first. Public Interface helloworld{ String Say (); }
Public classhelloworldimpl{ PublicString Say () {System. out. println ("Hello World in proxyhelloworldimpl!"); return "Hello world!"; }}/** * proxy class*/ Public classDynamicproxy implements Invocationhandler {
PrivateObject Target;
Publicobject Newinstance (object target) { This. target =Target; //This here represents the Invocationhandler object, which is the Dynamicproxy class returnProxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getclassinterfaces (), This); } Publicobject Invoke (Object Proxy,method method,object[] args) throws throwable{System. out. println ("before proxy"); //target object args: The parameter passed in, such as the method of adjusting the target objectMethod.invoke (Target,args); System. out. println ("before proxy"); return NULL; }}
Write a main class
Public proxymain{ public staticvoidnew new Helloworldimpl ()' HelloWorld hwp =(HelloWorld) dp.newinstance (HW); Hwp.say (); }}
Execution results
Before proxy!
Hello World in proxyhelloworldimpl!
After proxy!
Another form of writing the Dynamicproxy class is:
Public dynamicproxy{private Object target; Public Dynamicproxy (Object target) {this.target = target; } Public object Invoke (Object Proxy,method method,object[] args) {System.out.println ("before proxy"); Method.invoke (Target,args); System.out.println ("After proxy"); }}/**
* All using the Proxy.newproxyinstance method to complete the proxy object
*/public proxymain{public void static main (string[] args) {HelloWorld hw = new Helloworldimpl (); Invocationhandler dp = new dynamicproxy (HW); HelloWorld hwi = (HelloWorld) proxy.newproxyinstance (helloworld.class.getclassloader,new class<?>[]{ Helloworld.class},DP); Hwi.say (); }}
The result of the execution is the same as the previous proxy class.
Cultivating internal strength--dynamic agent