Java Dynamic proxy mode initial solution

Source: Internet
Author: User
Part 1
1. Role and definition of proxy mode: provides a proxy for other objects to control access to this object. In some cases, a client does not want or cannot directly reference another object, and the proxy object can play a mediation role between the client and the target object.
2. roles involved in proxy Mode
Abstract role: Declares the common interfaces of real objects and proxy objects. It is generally declared as an abstract class or interface.
Proxy role: the proxy object role contains a reference to the real object to operate on the real object. At the same time, the proxy object provides the same interface as the real object to replace the real object at any time. At the same time, the proxy object can append other operations when performing real object operations, which is equivalent to encapsulating real objects.
Real role: the real object represented by the proxy role is the object we finally want to reference.
3. Example of three roles
Abstract role package proxypattern;

Public interface subject ...{

Public void dothing ();
}

The real role implements the dothing () method of the subject; Package proxypattern;

Public class realsubject implements subject ...{
Public realsubject ()...{

}

Public void dothing ()...{
System. Out. println ("do you want do .");
}
}

Proxy role:
Package proxypattern;

Public class proxysubject implements subject ...{

Public realsubject;
Public proxysubject ()...{

}

Public void dothing ()...{
Predothing ();
If (realsubject = NULL )...{
Realsubject = new realsubject ();
}
Realsubject. dothing (); // execute the dothing () method of the real object
Afterdothing ();
}

Private void predothing ()...{
System. Out. println ("before you do thing! ");
}
Private void afterdothing ()...{
System. Out. println ("after you do thing! ");
}

}

Test Case package proxypattern;

Public class proxytest ......{

/***//***//***//**
* @ Param ARGs
*/
Public static void main (string [] ARGs )......{

Subject sub = new proxysubject ();

Sub. dothing ();
}

}

4. If you want to use the proxy mode according to the preceding method, the real role must exist beforehand and act as the internal attribute of the proxy object. However, in actual use, a real role must correspond to a proxy role. If a large number of roles are used, the class will expand sharply. In addition, if you do not know the real role, how can you use the proxy? This problem can be solved through the dynamic proxy class of Java 5. if you want to use the proxy mode according to the above method, the real role must exist beforehand and use it as the internal attribute of the proxy object. However, in actual use, a real role must correspond to a proxy role. If a large number of roles are used, the class will expand sharply. In addition, if you do not know the real role, how can you use the proxy? This problem can be solved through the dynamic proxy class of Java.

Part 2
. Dynamic proxy

The Java Dynamic proxy class is located under the java. Lang. Reflect package and generally involves the following two classes:

(1). Interface invocationhandler: this interface defines only one method object: invoke (Object OBJ, method, object [] ARGs ). In actual use, the first parameter OBJ generally refers to the proxy class, and the method is the proxy method. In the preceding example, dothing () and ARGs are the parameter arrays of this method. This abstract method is dynamically implemented in the proxy class.

(2). Proxy: this class is a dynamic proxy class, which is similar to proxysubject in the previous example. It mainly includes the following content:

Protected proxy (invocationhandler h): constructor, which is used to assign values to the internal H.

Static class getproxyclass (classloader loader, class [] interfaces): obtains a proxy class. loader is the class loader, and interfaces is the array of all interfaces of the real class.

Static object newproxyinstance (classloader loader, class [] interfaces, invocationhandler h): returns an instance of the proxy class, the returned proxy class can be used as a proxy class (the method declared in the subject interface of the proxy class can be used ).

Dynamic proxy is such a class: it is a class generated at runtime. You must provide a set of interfaces to it when generating it, then the class declares that it implements these interfaces. Of course, you can use the class instance as any of these interfaces. Of course, this dynamic proxy is actually a proxy, and it will not do substantial work for you. When generating its instance, you must provide a handler to take over the actual work.

Proxy role package dynamicproxy;

Import java. Lang. Reflect. invocationhandler;
Import java. Lang. Reflect. method;

Public class dynamicsubject implements invocationhandler ...{

Public dynamicsubject ()...{


}

Public dynamicsubject (Object OBJ )...{

Sub = OBJ;
}

Private object sub;

Public object invoke (Object proxy, method, object [] ARGs)
Throws throwable ...{
// Todo auto-generated method stub
System. Out. println ("before you do thing ");
Method. Invoke (sub, argS );
System. Out. println ("after you do thing ");
Return NULL;
}



}

The internal attribute of the proxy class is the object class. In actual use, the class's constructor dynamicsubject (Object OBJ) is used to assign values to it. In addition, the invoke method is also implemented in this class.

Method. Invoke (sub, argS );

Actually, it is to call the method to be executed by the proxy object. The method parameter sub is the actual proxy object, and ARGs is the parameter required to execute the corresponding operation of the proxy object. Through the dynamic proxy class, we can execute some related operations before or after the call.

Call the example package dynamicproxy;

Import java. Lang. Reflect. invocationhandler;
Import java. Lang. Reflect. proxy;

Import proxypattern. realsubject;
Import proxypattern. subject;

Public class client ...{

/***//**
* @ Param ARGs
*/
Public static void main (string [] ARGs) throws throwable ...{
// Todo auto-generated method stub
Realsubject rs = new realsubject ();
Invocationhandler DS = new dynamicsubject (RS );
Class CLS = Rs. getclass ();
Subject subject = (subject) proxy. newproxyinstance (CLS. getclassloader (), CLS. getinterfaces (), DS );
Subject. dothing ();
}

}

In this way, the realsubject object can be dynamically changed at runtime, and the subject interface to be controlled can be changed at runtime (dynamicsubject class) it can also be dynamically changed to achieve a Flexible Dynamic proxy relationship.

Cglib

Implement AOP Using cglib

Cglib is different from the implementation solution provided by the java standard library. cglib is mainly implemented by extending a subclass Based on the implementation class (such as studentinfoserviceimpl. Java. Corresponds to the proxy and invocationhandler in the dynamic proxy, net. SF. cglib. proxy. enhancer and methodinterceptor are responsible for creating proxy objects and intercepting methods in cglib. They generate subclass of the target class instead of implementing method interception through interfaces, enhancer is mainly used to construct dynamic proxy subclass to implement interception. methodinterceptor (Extended callback Interface) is mainly used to implement the concept of AOP und advice (AOP ):

1) Our business processing (studentinfoserviceimpl. Java ):
Public class studentinfoserviceimpl {
Public void findinfo (string name ){
System. Out. println ("your current name is:" + name );
}
}
2) implement a tool to process logs (aopinstrumenter. Java ):
Import net. SF. cglib. Proxy. methodinterceptor;
Import net. SF. cglib. Proxy. enhancer;
Import net. SF. cglib. Proxy. methodproxy;
Import java. Lang. Reflect. method;
Import org. Apache. log4j. Logger;

Public class aopinstrumenter implements methodinterceptor {
Private logger log = logger. getlogger (aopinstrumenter. Class );
Private enhancer = new enhancer ();

Public object getinstrumentedclass (class clz ){
Enhancer. setsuperclass (clz );
Enhancer. setcallback (this );
Return enhancer. Create ();
}

Public object intercept (Object o, method, object [] ARGs, methodproxy proxy) throws throwable {
Log.info ("call log method" + method. getname ());
Object result = proxy. invokesuper (O, argS );
Return result;
}

}
3) Let's test (aoptest. Java ):
Public class aoptest {
Public static void main (string [] ARGs ){
Aopinstrumenter instrumenter = new aopinstrumenter ();
Studentinfoserviceimpl studentinfo = (studentinfoserviceimpl) instrumenter. getinstrumentedclass (studentinfoserviceimpl. Class );
Studentinfo. findinfo ("A Fei ");
}
}
The output result is the same as the preceding one.
Cglib provides classes for the above purpose
1) enhancer: setcallback (callback), setsuperclass (class), create () returns the dynamic subclass object
2) the interface required by methodinterceptor: intercept (object, method, object [], methodproxy) returns the result of the original method call. The principle is the same as that of proxy.

 

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.