A study of dynamic agent mechanism in Java

Source: Internet
Author: User

Java Dynamic load Class (reflection mechanism)
/*Myclass.java*/ Public classMyClass { Public intID;  PublicString name;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicMyClass (intID, String name) {         This. ID =ID;  This. Name =name; }     PublicMyClass (intID) { This. ID =ID; }     Public voidSayhallo () {System.out.println ("Hallo" + This. GetName () + ", your ID is:" + This. GetId ()); }}/*Main.java*/ Public classMain { Public Static voidmain (String [] args) {Try{            //specify which construction method to use according to the parameter table (Int.class)            /** There is also an interview question, "The return value is different, the parameters of the same two Java methods, can exist?"            As you can see from here, if a method has only a different return value, we cannot define one of the methods by using the same invocation parameters. */Constructor Constructor= Class.forName ("Com.yy.MyClass"). GetConstructor (int.class); Object Object= Constructor.newinstance (10); Method Method= Class.forName ("MyClass"). GetMethod ("Sayhallo"));            Method.invoke (object); Field field= Class.forName ("MyClass"). GetField ("id")); Integer ID=Field.getint (object); }        Catch(Exception e) {e.printstacktrace (); }    }}

What about this dynamic loading class mechanism (also known as the reflection mechanism)? From the code we can see that we construct an instance of it without knowing the target MyClass (only its class name and method). and invoke its internal methods and properties like an object constructed from a normal constructor method. And all of this is based on the simple condition that we know its name.
So what can this do? First, without looking at the code, first from the logical level to infer how such a feature can achieve the magical function.

    • Because we only need to know the class name to Class.forName("MyClass").getConstructor(int.class); get the constructor of the class and construct its instance. Well, we only know the class name, and before the code really runs, we don't even know if the class really exists (in other words, we don't know if there's a compiled. class file). You can also make yourself this part of the code by compiling. It's scary, isn't it? Indeed, this gives our code a risk of completeness if we cannot find the class that we specified by name. The familiar ClassNotFoundException will appear. However, the benefits of this change are the flexibility to allow each part of the project to be independent of each other's code. You can dynamically invoke ClassLoader the .class文件 load into a virtual machine and then use the methods in it. This makes it possible to dynamically link program components.
    • Also, because we can skip the target code itself, call the method directly in it. According to the idea of various design patterns, can we do some articles when invoking the method? For example, make a log, format the parameters, change the business logic. And more importantly, we don't touch the target code yet. This lays the groundwork for AOP.
Dynamic Agent

A word summary dynamic agent, is 通过动态加载类的方式实现的代理模式 .
So, in essence, dynamic proxies are also a subset of proxies. Steal a picture to see a purely proxy model.

The direct operation of the user is Proxy that, because it is the same as the implementation of the RealSubject Subject pretext, so that the method defined in the interface can be used in or at will Proxy . In RealSubject fact Proxy , internally by preserving an RealSubject object to achieve this consistency, it seems to have borrowed The Proxy agent of the hand to access RealSubject . This is the simple proxy mode.
The dynamic agent simply means that on this basis the RealSubject instantiation is changed from simple creation to new dynamic creation. It's too simple, but the core is the idea.

Before you look at the official Java implementation, take a look at a simple example of your own writing. It explains what dynamic proxies are and the benefits of dynamic proxies.

* Target interface required for proxy */ Public Interfacemyproxy {intAddintArg1,intarg2);}/*proxy class*/ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classMyproxyimplImplementsmyproxy {protectedInvocationhandler Handler;  PublicMyproxyimpl (Invocationhandler handler) { This. Handler =handler; } @Override Public intAddintArg1,intarg2) {Method Method=NULL; Try{method= myproxy.class. GetMethod ("Add",Newclass[]{int.class,int.class}); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Object result=NULL; Try{result= Handler.invoke ( This, Method,Newobject[]{NewInteger (ARG1),NewInteger (ARG2)}); } Catch(Throwable throwable) {throwable.printstacktrace (); }        return(Integer) result; }}/*the real execution method of the handler, here using a+b+ ... method to calculate the Add () method*/ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classMyHandlerImplementsInvocationhandler { PublicMyHandler () {} @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {if(Method.getname (). Equals ("Add") {Integer sum= 0;  for(Object object:args) {sum= (Integer) object +sum; }            returnsum; }        Else {            return NULL; }    }}/*The real execution method of the Handler2, unlike handler, this class put the Add () method according to A*b ... method to Process **/ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classMyHandler2ImplementsInvocationhandler { PublicMyHandler2 () {} @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {if(Method.getname (). Equals ("Add") {Integer sum= 1;  for(Object object:args) {sum= (Integer) Object *sum; }            returnsum; }        Else {            return NULL; }    }}/*Business Class*/ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.InvocationHandler;Importjava.lang.reflect.InvocationTargetException; Public classMymain { Public Static voidMain (String [] args)throwsclassnotfoundexception, Nosuchmethodexception, Illegalaccessexception, InvocationTargetException, instantiationexception {//simply modifying the name of the class that actually executes the add () method invokes both algorithms in full consistency. The business code does not have to be modified. //Conversely, if the class name in the business code does not change, no matter how MyHandler implements the Add () method, it is possible.Class cl = Mymain.class. forname ("Com.yy.MyHandler"); //Class cl = MyMain.class.forName ("Com.yy.MyHandler2");Constructor Constructor =Cl.getconstructor (); Invocationhandler Invocationhandler=(Invocationhandler) constructor.newinstance (); Myproxy myproxy=NewMyproxyimpl (Invocationhandler); Integer I= Myproxy.add (32,18);    System.out.println (i); }}

With this example, we can see the use of dynamic proxies. On the one hand, we can ensure that the business code is decoupled from the underlying code implementation, and on the other, it can be decorated with any underlying component that might be added. For example, we can MyProxyImpl.add() make the following changes

@Override Public intAddintArg1,intarg2) {System.out.println ("The calculated parameters are:" + arg1 + "," + arg2);//add this line.Method method =NULL; Try{method= myproxy.class. GetMethod ("Add",Newclass[]{int.class,int.class}); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Object result=NULL; Try{result= Handler.invoke ( This, Method,Newobject[]{NewInteger (ARG1),NewInteger (ARG2)}); } Catch(Throwable throwable) {throwable.printstacktrace (); }        return(Integer) result; }

Notice that we have added a line of code that allows any operation that calls the Add () method through the proxy to print out the parameters. Whether you are calling Hander1 or Handler2 at the bottom. Is it convenient?

Of course, we have so-called dynamic agents have a lot of problems, the following is to see the Java official use of proxy implementation of the dynamic proxy mechanism.

Java.lang.reflect.Proxy

Through the official proxy, to implement the above code logic, you can write:

 Public classMymain { Public Static voidMain (String [] args)throwsclassnotfoundexception, Nosuchmethodexception, Illegalaccessexception, InvocationTargetException, instantiationexception {Class cl= Mymain.class. forname ("MyHandler"); Constructor Constructor=Cl.getconstructor (); Invocationhandler Invocationhandler=(Invocationhandler) constructor.newinstance (); Myproxy myproxy= (myproxy) proxy.newproxyinstance (Mymain.class. getClassLoader (),NewClass[]{myproxy.class},invocationhandler); Integer result= Myproxy.add ();    SYSTEM.OUT.PRINTLN (result); }}

The heart Proxy.newProxyInstance(MyMain.class.getClassLoader(),new Class[]{MyProxy.class},invocationHandler); of the reader will find that, in fact, here with our own implementation of a poor MyProxyImpl implementation of the class. We end up invoking an instance object of the class MyProxyImpl , and the official method is invoking an MyProxy instance object of the interface.
And, if you try to get an instance object of an implementation class, it will say that Myproxyimpl is not an interface!

Myproxyimpl myproxy = (Myproxyimpl) proxy.newproxyinstance (mymain.  Class. getClassLoader (),new Class[]{myproxyimpl.  Class},invocationhandler); Interface

See that the Proxy class has a private internal static class ProxyClassFactory , which is used to get the class instance. There is a apply() method in it that iterates through Proxy.newProxyInstance() all the classes passed in by the second argument is not an interface.

/*   * Verify that the Class object actually represents an  * interface.   */ if (! Interfaceclass.isinterface ()) {     thrownew  illegalargumentexception (         + "isn't an interface");}

So we have the above error. So, now the question becomes why does proxy have to make this restriction? The simple understanding is that Java's single-inheritance mechanism determines. If the second argument comes in multiple entity classes, they cannot instantiate an object.

A study of dynamic agent mechanism in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.