Why a dynamic proxy is used by a Java dynamic agent
When a method of a class needs to be decorated (enhanced), you can use inheritance, decorator mode, and dynamic proxy.
Three ways of limiting:
- Inheritance: Enhanced objects cannot be changed, and enhanced content cannot be changed.
- Decorator mode: The enhanced object cannot be changed and the enhanced content can be changed.
- Dynamic proxies: Enhanced objects can be changed, and enhanced content can be changed.
Using dynamic proxies gives you more flexibility in increasing the reusability of your code.
Give me a chestnut:
For computer teachers This class, there is a teach () method, the past, the old teaching mode may not be suitable for the rapid development of the computer industry, so in the use of this teach () method may need to add something in front or behind. But for older projects, it's hard to understand the way they are written and thought, so we can't easily modify their code, so we can use proxies to implement enhancements to the Teach () method (I'm divided into pre-and post-enhancement).
How to use Dynamic proxy object Proxy.newinstance (ClassLoader loader, class[] interfaces, Invocationhandler IH)
- Loader: Class loader, loading classes into memory.
- Interfaces: The interface to be implemented by the proxy object.
- Ih:invocationhandler, which implements the Invoke () method, to implement enhancements to the target object.
- Return value: An object generated dynamically by the JVM runtime, which is not our invocationhandler type, nor the type of the set of interfaces we define, but rather a dynamically generated object that runs
Invocationhandler interface
The interface needs to implement the Invoke () method.
Object Invoke (Object proxy, Method method, object[] args)
- Proxy: Agent object.
- Method: The target approach used by the proxy object.
- Args: The parameters of the target method.
- Return value: The return value of the methods method.
When using a method with a proxy object, the Invoke () method of the Invocationhandler that is passed in when the proxy object is generated is called, so you can write content that needs to be enhanced in this invoke ().
Demo
First, give two interfaces and an implementation class
publicinterface Subject { publicintoutPut(int num);}
public bsubject {public int output2 (int num);}
public class Realsubject implements Subject, Bsubject { @Override public int
output (
int num) {system.
. println ( "OutPut" + String. valueof (num) + "people" ); return num; } @Override public int (int num) {system.. println ( "OutPut2" + String. valueof (num) + "people" ); return num; }}
Using dynamic proxies
Front-mounted Enhancement interface:
publicinterface// 前置增强接口 publicvoidbefore();}
Post-enhanced Interface:
publicinterface// 后置增强接口 publicvoidafter();}
Creating a proxy factory makes it easier to invoke:
import Java.lang.reflect.InvocationHandler;import Java.lang.reflect.Method;import Java.lang.reflect.Proxy; Public classproxyfactory {PrivateObject TargetObject;//Target Agent object PrivateBeforeadvance beforeadvance;//front-mounted enhancements PrivateAfteradvance afteradvance;//rear-mounted enhancements PublicObjectcreatefactory() {ClassLoader loader = This.GetClass().getClassLoader();//load. class to MemoryClass[] interfaces = TargetObject.GetClass().getinterfaces();///Get Realsubject all Interfaces (waiter), provide a set of interfaces to the proxy object, this proxy object will implement this set of interfaces,Invocationhandler ih =NewInvocationhandler () {@Override /Proxy is a proxy object, a dynamically generated object at the runtime of the JVM, it is not our invocationhandler type, nor is it the type of the set of interfaces we define, but rather a dynamically generated object that runs //method is the way the target object needs to be enhanced //args is an argument PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsThrowable {if(Beforeadvance! =NULL) {//Call forward enhancement methodBeforeadvance.before(); } Object result = method.Invoke(TargetObject, args);//Call the target method of the target proxy object by reflection, result is the return value of the target method if(Afteradvance! =NULL) {//Call the post-enhancement methodAfteradvance. After(); }returnResult } };returnProxy.newproxyinstance(loader, interfaces, IH);//Get a proxy object} PublicAfteradvancegetafteradvance() {returnAfteradvance; } Public void setafteradvance(Afteradvance afteradvance) { This.afteradvance= Afteradvance; } PublicBeforeadvancegetbeforeadvance() {returnBeforeadvance; } Public void setbeforeadvance(Beforeadvance beforeadvance) { This.beforeadvance= Beforeadvance; } PublicObjectGettargetobject() {returnTargetObject; } Public void Settargetobject(Object TargetObject) { This.TargetObject= TargetObject; }}
Example:
import org.junit.Test; Public classDemo {@Test Public void Fun() {Proxyfactory proxyfactory =New proxyfactory();//target object for the agentProxyfactory.Settargetobject(New Realsubject());//Pre-enhanced interface implementationProxyfactory.setbeforeadvance(New beforeadvance() {@Override Public void before() {System. out.println("Hello"); } });//rear-mounted enhanced interface implementationProxyfactory.setafteradvance(New afteradvance() {@Override Public void After() {System. out.println("Byebye"); } });//Generate an implementation class object for the subject interfaceSubject Subject = (Subject) proxyfactory.createfactory();//through newinstance () to get a proxy object, this proxy object implements the subject interface, so it can be strongly converted to subject interface class. Bsubject Subject2 = (bsubject) proxyfactory.createfactory(); Object result = subject.OutPut( -);//corresponding to the Invocationhandler invoke method: Subject as proxy, output as method, parameter argsSystem. out.println(result); System. out.println("-----"); Object result2 = Subject2.OutPut2( -); System. out.println(RESULT2); }} Output: Hellooutput -Peoplebyebye ------HELLOOUTPUT2 -Peoplebyebye -
In this case, as long as the use of reflection, Method.invoke () can invoke the proxy target object of the method, and then implement the pre-enhanced Beforeadvance interface and the post-enhanced Afteradvance interface, you can implement the method to enhance the content.
Beforeadvance and afteradvance can be reused by different implementations of different interfaces.
For different enhancement objects can also be used, as long as the targetobject to change a bit.
Attach a good article to the story
Dynamic agent of Java learning