Understanding: Dynamic agent is mainly used to do the enhancement of methods, so that you can not modify the source of the situation, to enhance some methods
The proxy object inherits the same interface as the Proxied object, and they do not inherit the relationship
Simulating the service layer of Java EE
1. Define the interface
Userservice.java
Public Interface UserService { publicvoid Save (); Public void Delete (); Public void update (); Public void find ();}
2. Define the Implementation class
Userserviceimpl.java
Public classUserserviceimplImplementsUserService { Public voidSave () {System.out.println (Save); } Public voidDelete () {System.out.println (Delete); } Public voidUpdate () {SYSTEM.OUT.PRINTLN (Update); } Public voidfind () {System.out.println (Find); }}
3. Enhanced Class
Userserviceproxyfactory.java
ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public classUserserviceproxyfactoryImplementsInvocationhandler {//the object to be enhanced Privateuserservice us; PublicUserserviceproxyfactory (userservice us) { This. US =us; } PublicUserService Getuserserviceproxy () {//Generating Dynamic Agents//Dynamic Agent parameter one: A ClassLoader object that defines which ClassLoader object to load on the generated proxy object//parameter two: the interface of the Proxied object, (an array of interface objects, which indicates that I am going to provide a set of interfaces to the object I need to proxy, and if I provide a set of interfaces to it, then this proxy object declares that the interface is implemented (polymorphic), So I can invoke the methods in this set of interfaces.)//parameter three: A Invocationhandler object that represents the Invocationhandler object to which the dynamic proxy object is associated when it calls the method ( Because inherit the Invocationhandler, so the parameter three can pass this)UserService usproxy = (userservice) proxy.newproxyinstance (userserviceproxyfactory.class. getClassLoader (), Userserviceimpl.class. Getinterfaces (), This); returnUsproxy; } //Enhancement Methods//Proxy: Refers to the real object that we are acting for//Method : Refers to the methods object that we want to invoke the real object//args: Refers to parameters that are accepted when a method of a real object is called Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//enhanced before calling the method contentSYSTEM.OUT.PRINTLN ("Open Transaction"); Object Invoke=Method.invoke (us, args); //enhanced after calling this methodSystem.out.println ("Close Things"); returninvoke; } }
4. Test class
Demo.java
Public class Demo { @Test publicvoid testproxy () { new Userserviceimpl (); New userserviceproxyfactory (US); = factory.getuserserviceproxy (); Usproxy.save (); } }
Java Dynamic Agent