Introduction to static and dynamic proxies in Java

Source: Internet
Author: User
I. Proxy Mode
The proxy mode is a common Java design mode. It features the same interface between the proxy class and the delegate class. The proxy class is mainly responsible for preprocessing, filtering, and forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class. A proxy class object is associated with a delegate class object. The proxy class object itself does not actually implement the service, but calls the relevant methods of the delegate class object, to provide specific services.

According to the creation period of the proxy class, the proxy class can be divided into two types.

Static proxy class:
The source code is automatically generated by the programmer or by a specific tool, and then compiled. Before running the program, the. Class file of the proxy class already exists.

Dynamic Proxy: dynamically created by using the reflection mechanism when the program is running.

Ii. Static proxy
As follows, the helloserviceproxy class is the proxy class, And the helloserviceimpl class is the delegate class, both of which implement the helloservice interface. The helloserviceimpl class is the real implementer of the helloservice interface, and the helloserviceproxy class provides specific services by calling the methods of the helloserviceimpl class. The echo () method and gettime () method of the helloserviceproxy class call the echo () method and gettime () method of the helloserviceimpl object to be proxy respectively, some simple printing operations will be performed before and after the method call.

It can be seen that the proxy class can pre-process messages for the delegate class, forward messages to the delegate class, and post-process messages.

Routine 1 helloservice. Java
Package proxy;
Import java. util. date;
Public interface helloservice {
Public String echo (string MSG );
Public date gettime ();
}
Routine 2 helloserviceimpl. Java
Package proxy;
Import java. util. date;
Public class helloserviceimpl implements helloservice {
Public String echo (string MSG ){
Return "Echo:" + MSG;
}
Public date gettime (){
Return new date ();
}
}
Example 3 helloserviceproxy. Java
Package proxy;
Import java. util. date;
Public class helloserviceproxy implements helloservice {
Private helloservice; // indicates the helloservice instance to be proxy
Public helloserviceproxy (helloservice ){
This. helloservice = helloservice;
}
Public void sethelloserviceproxy (helloservice ){
This. helloservice = helloservice;
}
Public String echo (string MSG ){
System. Out. println ("before calling echo ()"); // preprocessing
String result = helloservice. Echo (MSG); // call the echo () method of the helloservice instance to be proxy
System. Out. println ("after calling echo ()"); // post-event processing
Return result;
}
Public date gettime (){
System. Out. println ("before calling gettime ()"); // preprocessing
Date = helloservice. gettime (); // call the gettime () method of the helloservice instance to be proxy
System. Out. println ("after calling gettime ()"); // post-event processing
Return date;
}
}
In the main () method of Client1 class, a helloserviceimpl object is created, a helloserviceproxy object is created, and the echo () method of the helloserviceproxy object is called.
Routine 4 client1.java
Package proxy;
Public class Client1 {
Public static void main (string ARGs []) {
Helloservice = new helloserviceimpl ();
Helloservice helloserviceproxy = new helloserviceproxy (helloservice );
System. Out. println (helloserviceproxy. Echo ("hello "));
}
}
Run the Client1 class and print the result as follows:
Before calling echo ()
After calling echo ()
Echo: Hello

The source code of the helloserviceproxy class in Example 3 is compiled by a programmer. Before the program runs, its. Class file already exists. This kind of proxy class is called a static proxy class.

3. Dynamic proxy
The dynamic proxy class compares with the static proxy class. The Byte Code of the dynamic proxy class is dynamically generated by the Java reflection mechanism when the program is running, without the need for programmers to manually write its source code. Dynamic proxy not only simplifies programming, but also improves the scalability of the software system, because the Java reflection mechanism can generate any type of dynamic proxy class. The proxy class and invocationhandler interface in the Java. Lang. Reflect package provide the ability to generate dynamic proxy classes.

The proxy class provides static methods for creating dynamic proxy classes and their instances.
(1) The getproxyclass () static method is used to create a dynamic proxy class. Its complete definition is as follows:

Public static class <?> Getproxyclass (classloader loader, class <?> [] Interfaces) throws illegalargumentexception

The loader parameter specifies the class loader of the dynamic proxy class, and the interfaces parameter specifies all interfaces to be implemented by the dynamic proxy class.

(2) The newproxyinstance () static method is used to create an instance of the dynamic proxy class. Its complete definition is as follows:

Public static object newproxyinstance (classloader loader, class <?> [] Interfaces, invocationhandler handler) throws
Illegalargumentexception

The loader parameter specifies the class loader of the dynamic proxy class, the interfaces parameter specifies all interfaces to be implemented by the dynamic proxy class, And the handler parameter specifies the invocationhandler object associated with the dynamic proxy class.

An instance of the dynamic proxy class implementing the foo interface is created in either of the following ways:
/***** Method 1 ****/
// Create invocationhandler object
Invocationhandler handler = new myinvocationhandler (...);

// Create a dynamic proxy class
Class proxyclass = proxy. getproxyclass (FOO. Class. getclassloader (), new class [] {Foo. Class });

// Create a dynamic proxy instance
Foo = (FOO) proxyclass. getconstructor (new class [] {invocationhandler. Class }).
Newinstance (new object [] {handler });

/***** Method 2 ****/
// Create invocationhandler object
Invocationhandler handler = new myinvocationhandler (...);

// Directly create a dynamic proxy instance
Foo = (FOO) proxy. newproxyinstance (FOO. Class. getclassloader (), new class [] {Foo. Class}, Handler );

A dynamic proxy class created by a static method of the proxy class has the following features:
The dynamic proxy class is public, final, and non-abstract;
The dynamic proxy class inherits the java. Lang. Reflect. proxy class;
The name of the dynamic proxy class starts with "$ proxy;
The dynamic proxy class implements all interfaces specified by interfaces in the getproxyclass () and newproxyinstance () methods;

Isproxyclass (class <?> Cl) static methods can be used to determine whether the class specified by the parameter is a dynamic proxy class. Only the classes created through the proxy class are dynamic proxy classes;

Dynamic proxy classes all have a public constructor. This constructor has an invocationhandler parameter.

An instance of a dynamic proxy class created by a static method of the proxy class has the following features:
1. If the variable foo is an instance of the dynamic proxy class and the dynamic proxy class implements the foo interface, the value of "foo instanceof foo" is true. It is legal to forcibly convert the variable Foo to the foo type:
(FOO) Foo // valid

2. Each dynamic proxy instance is associated with an invocationhandler instance. The getinvocationhandler (Object proxy) Static Method of the proxy class returns the invocationhandler object associated with the proxy instance specified by the proxy parameter.

3. assume that the foo interface has an amethod () method. When the program calls the amethod () method of the dynamic proxy instance Foo, this method calls the invoke () of the invocationhandler object associated with it () method.

The invocationhandler interface is a method call interface, which declares the invoke () method used to call any method:
Object invoke (Object proxy, method, object [] ARGs) throws throwable

The parameter proxy specifies a dynamic proxy instance, the parameter method specifies the called method, and the parameter ARGs specifies the parameter passed to the called method. The return value of the invoke () method indicates the return value of the called method.

4. Finally, let's look at an instance:
The gethelloserviceproxy () Static Method of the helloserviceproxyfactory class is responsible for creating instances of dynamic proxy classes that implement the helloservice interface.

Routine 5 helloserviceproxyfactory. Java
Package proxy;
Import java. Lang. Reflect .*;
Public class helloserviceproxyfactory {
/** Create a dynamic proxy instance that implements the helloservice Interface
* The helloservice parameter references the helloservice instance of the proxy.
*/
Public static helloservice gethelloserviceproxy (final helloservice ){
// Create an instance of an anonymous class that implements the invocationhandler Interface
Invocationhandler handler = new invocationhandler (){
Public object invoke (Object proxy, method, object ARGs []) throws exception {
System. Out. println ("before calling" + method); // preprocessing
Object result = method. Invoke (helloservice, argS );
// Call the helloservice instance of the proxy
System. Out. println ("after calling" + method); // post-event processing
Return result;
}
};
Class classtype = helloservice. Class;
Return (helloservice) proxy. newproxyinstance (classtype. getclassloader (),
New Class [] {classtype },
Handler );
}
}
As shown below, Client2 creates a helloserviceimpl instance first, creates a dynamic proxy instance helloserviceproxy, and finally calls the echo () method of the dynamic proxy instance.
Routine 6 client2.java
Package proxy;
Public class Client2 {
Public static void main (string ARGs []) {
Helloservice = new helloserviceimpl ();
Helloservice helloserviceproxy = helloserviceproxyfactory. gethelloserviceproxy (helloservice );
System. Out. println ("the name of the dynamic proxy class is" + helloserviceproxy. getclass (). getname ());
System. Out. println (helloserviceproxy. Echo ("hello "));
}
}
Run Client2 and print the result as follows:
The dynamic proxy class is named $ proxy0.
Before calling public abstract java. Lang. String proxy. helloservice. Echo (Java. Lang. String)
After calling public abstract java. Lang. String proxy. helloservice. Echo (Java. Lang. String)
Echo: Hello
The result shows that the dynamic proxy class is named $ proxy0.

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.