Java proxy mode

Source: Internet
Author: User

Java proxy mode and dynamic proxy class 2005-03-08 14:22 7483 people read reviews (3) Favorite Report Javaobjectclassinterfaceimportconstructor Understanding of proxy mode and Java Dynamic proxy class

1. Proxy Mode

The role of proxy mode is to provide a proxy for other objects to control access to this object. In some cases, one customer does not want or cannot refer to another object directly, whereas a proxy object can act as an intermediary between the client and the target object.

The agent model generally involves the following roles:

abstract Role : a common interface for declaring real objects and proxy objects;

Proxy Role : The proxy object role contains a reference to the real object, allowing you to manipulate the real object while the proxy object provides the same interface as the real object to replace the real object at any moment. At the same time, the proxy object can attach other actions when performing the real object operation, which is equivalent to encapsulating the real object.

Real role : The real object represented by the proxy role is the object we end up referencing. (See document 1)

Here's an example of the examples in Java and patterns:

Abstract roles:

Abstract public class Subject

{

Abstract public void request ();

}

Real character: implements the request () method of subject.

public class Realsubject extends Subject

{

Public Realsubject ()

{

}

public void Request ()

{

System.out.println ("from real subject.");

}

}

Agent role:

public class Proxysubject extends Subject

{

Private Realsubject Realsubject; Attributes with a real role as a proxy role

Public Proxysubject ()

{

}

public void request ()//This method encapsulates the request method of the Real object

{

Prerequest ();

if (Realsubject = = null)

{

Realsubject = new Realsubject ();

}

Realsubject.request (); The request method for performing real objects here

Postrequest ();

}

private void Prerequest ()

{

Something want to do before requesting

}

private void Postrequest ()

{

Something you want to does after requesting

}

}

Client calls:

Subject sub=new proxysubject ();

Sub.request ();

As can be seen from the above code, the customer actually needs to call the Realsubject class request () method, now use Proxysubject to proxy the Realsubject class, also to achieve the purpose, but also encapsulates the other methods (Prerequest (), Postrequest ()), you can handle some other issues.

In addition, if you want to use the proxy mode as described above, the real role must be pre-existing and used as the internal property of the proxy object. But when used in practice, a real role must correspond to a proxy role, and if a large number of uses would cause the class to swell dramatically, how would you use a proxy if you didn't know the real role beforehand? This problem can be solved by the dynamic proxy class in Java.

2. Dynamic proxy class

The Java dynamic proxy class is located under the Java.lang.reflect package, which generally involves the following two classes:

(1). Interface Invocationhandler: Only one method Object:invoke (Object Obj,method method, object[] args) is defined in this interface. When actually used, the first parameter, obj, generally refers to the proxy class, which method is the proxy, as in the previous example, the request (), args is the parameter array for the method. This abstract method is implemented dynamically in the proxy class.


(2). Proxy: This class is a dynamic proxy class that acts like the proxysubject in the previous example, which mainly includes the following:

Protected Proxy (Invocationhandler H): constructor, estimated to be used to assign values to internal H.

Static class Getproxyclass (ClassLoader loader, class[] interfaces): Gets a proxy class, where loader is a class loader, and interfaces is an array of all the interfaces owned by 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 (you can use a method declared in the subject interface of the proxy class).


The so-called dynamic Proxy is a class that is generated at runtime and you have to provide a set of interface to it when it is generated, and then the class declares that it implements these interface. You can certainly use this class instance as any of these interface. Of course, this dynamic proxy is actually a proxy, it will not do a substantial job for you, in the generation of its instance you must provide a handler, it takes over the actual work. (See document 3)

When using dynamic proxy classes, we must implement the Invocationhandler interface with the example in the first section:

Abstract Roles (previously an abstract class, which should be changed to an interface here):

public interface Subject

{

Abstract public void request ();

}

Specific Roles Realsubject: Ibid.;

Agent role:

Import Java.lang.reflect.Method;

Import Java.lang.reflect.InvocationHandler;

public class Dynamicsubject implements Invocationhandler {

Private Object Sub;

Public Dynamicsubject () {

}

Public dynamicsubject (Object obj) {

Sub = obj;

}

public object invoke (object proxy, Method method, object[] args) throws Throwable {

System.out.println ("before calling" + method);

Method.invoke (Sub,args);

System.out.println ("After calling" + method);

return null;

}

}

The internal property of the proxy class is the object class, which is actually assigned by the constructor of the class Dynamicsubject (object obj), and in addition, the Invoke method is implemented in the class, and the

Method.invoke (Sub,args);

In fact, it is the method that invokes the object being executed, the method parameter sub is the actual proxy object, and args is the parameter required to perform the corresponding operation of the Proxied object. With dynamic proxy classes, we can perform some related operations before or after the call.

Client :

Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Proxy;

Import Java.lang.reflect.Constructor;

Import Java.lang.reflect.Method;

public class Client

{

static public void Main (string[] args) throws Throwable

{

Realsubject rs = new Realsubject (); The proxy class is specified here

Invocationhandler ds = new Dynamicsubject (RS); Initialize the proxy class

Class cls = Rs.getclass ();

The following are the decomposition steps

/*

Class C = Proxy.getproxyclass (Cls.getclassloader (), cls.getinterfaces ());

Constructor ct=c.getconstructor (New Class[]{invocationhandler.class});

Subject Subject = (Subject) ct.newinstance (New Object[]{ds});

*/

The following is a one-time build

Subject Subject = (Subject) proxy.newproxyinstance (Cls.getclassloader (),

Cls.getinterfaces (), DS);


Subject.request ();

}

In this way, the Proxied object (Realsubject) can be dynamically changed at runtime, the interface that needs to be controlled (subject interface) can be changed at run time, the control mode (Dynamicsubject Class) can also be changed dynamically, thus achieving a very flexible dynamic agent relationship (See document 2).

Original address: http://blog.csdn.net/dyh8818/article/details/314668

Java Dynamic Agent One--the use of dynamic class proxy

1. What is a dynamic agent?

A: Dynamic agents can provide access to another object while hiding the exact facts of the actual object. The agent generally implements the interface of the actual object it represents. The agent can access the actual object, but delay the realization of some functions of the actual object, the actual object realizes the actual function of the system, and the proxy object hides the actual object from the customer. The customer does not know whether it deals with the agent or with the actual object.
2. Why use dynamic agents?

A: Because the dynamic agent can do any processing of the request

3. What are the benefits of using it?

A: Because the dynamic agent can do any processing of the request
4. Where do I need dynamic proxies?

A: Do not allow direct access to certain classes, special handling for access, etc.

Support for dynamic proxies is currently included in the Java development package, but its implementation supports only the implementation of interfaces . Its implementation is mainly through the Java.lang.reflect.Proxy class and the Java.lang.reflect.InvocationHandler interface.

The proxy class is primarily used to obtain dynamic proxy objects, which are used by the Invocationhandler interface to constrain the caller implementation

The following is a simulation case where a two-sentence string is output to the console before and after a method call through a dynamic proxy implementation

Directory structure

<br/>

Define a HelloWorld interface

1 package com.ljq.test;
2
3/**
4 * Define a HelloWorld interface
5 *
6 * @author Jiqinlin
7 *
8 */
9 public interface HelloWorld {
Ten public void SayHelloWorld ();
11}

<br/>

Class Helloworldimpl is the implementation of the HelloWorld interface

1 package com.ljq.test;
2
3/**
4 * Class Helloworldimpl is the implementation of the HelloWorld interface
5 *
6 * @author Jiqinlin
7 *
8 */
9 public class Helloworldimpl implements helloworld{
10
One public void SayHelloWorld () {
System.out.println ("helloworld!");
13}
14
15}

HelloWorldHandler is a Invocationhandler interface implementation

1 package com.ljq.test;
2
3 Import Java.lang.reflect.InvocationHandler;
4 Import Java.lang.reflect.Method;
5
6/**
7 * Implementation outputs two lines of string to the console before and after a method call
8 *
9 * @author Jiqinlin
10 *
11 */
public class HelloWorldHandler implements invocationhandler{
13//original object to be proxied
+ Private Object obj;
15
Public HelloWorldHandler (Object obj) {
+ Super ();
This.obj = obj;
19}
20
21/**
22 * Process The method call on the proxy instance and return the result
23 *
* @param proxy class
* @param method is proxied
* @param args The parameter array of the method
27 */
-Public object Invoke (object proxy, Method method, object[] args) throws Throwable {
Object result = null;
30//Before call
Dobefore ();
32//method of invoking the original object
Result=method.invoke (obj, args);
34//After call
Doafter ();
return result;
37}
38
$ private void Dobefore () {
System.out.println ("Before method Invoke");
41}
42
$ private void Doafter () {
System.out.println ("After method Invoke");
45}
46
47}

Test class

Package com.ljq.test;

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Proxy;


public class HelloWorldTest {

public static void Main (string[] args) {
HelloWorld helloworld=new Helloworldimpl ();
Invocationhandler handler=new HelloWorldHandler (HelloWorld);

To create a dynamic proxy object
HelloWorld proxy= (HelloWorld) proxy.newproxyinstance (
Helloworld.getclass (). getClassLoader (),
Helloworld.getclass (). Getinterfaces (),
handler);
Proxy.sayhelloworld ();
}
}

Original address: http://www.cnblogs.com/linjiqin/archive/2011/02/18/1957600.html

Java proxy mode

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.