Java implementation Dynamic Proxy _java

Source: Internet
Author: User
Tags object object static class throwable

The Java dynamic proxy class is located under the Java.lang.reflect package, typically involving the following two classes:
(1) Invocationhandler: Only one method is defined in this interface
public object Invoke (object Obj,method method, object[] args)
In practice, the first parameter, obj, generally refers to the proxy class, which is the proxy method, as in the previous example, the request (), which is args as an array of arguments for the method. This abstract method is dynamically implemented in the proxy class.

(2) Proxy: The class is a dynamic proxy class, and acts like the proxysubject in the previous example, which mainly contains the following contents protected Proxy (Invocationhandler h): constructor, for assigning internal H.
Static Class Getproxyclass (ClassLoader loader, class[] interfaces)
Get 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 that can be used as a proxy class (you can use the method declared in the subject interface of the proxy class)

Dynamic Proxy is a class that is generated at run time and you must 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 an instance of this class as any of these interface. Of course, this dynamic proxy is actually a proxy, and it won't do any real work for you, and you have to provide a handler to take over the actual work when generating an instance of it.

When using a dynamic proxy class, we must implement the Invocationhandler interface:
See program Subject.java
See program Realsubject.java
See program Dynamicsubject.java
See program Client.java

Copy Code code as follows:

Package com.langsin.dynamicproxy;
Abstract role (previously an abstract class, which should be changed to interface):
public interface Subject
{
Abstract public void request ();
}

Copy Code code as follows:

Package com.langsin.dynamicproxy;
Specific roles
public class Realsubject implements Subject
{
Public Realsubject ()
{

}
public void Request ()
{
System.out.println ("from real subject.");
}
}

Copy Code code as follows:

Package com.langsin.dynamicproxy;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Agent processor
/**
* The intrinsic property of the proxy class is the Object class, which is assigned a value by the constructor Dynamicsubject (object obj) of the class when it is actually used;
* In addition, the Invoke method is implemented in this class, the Method.invoke (Sub,args) in the method;
* is actually the method that invokes the object to be executed, the method parameter sub is the actual proxy object,
* Args the parameters required to perform the corresponding operation of the proxy object.
* Through the dynamic proxy class, we can perform some related operations before or after the call
*/
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 the Calling" + method);
return null;
}
}

Copy Code code as follows:

Package com.langsin.dynamicproxy;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Proxy;
Client
public class Client
{
static public void Main (string[] args) throws Throwable
{
Realsubject rs = new Realsubject (); Specify the proxy class here
Invocationhandler ds = new Dynamicsubject (RS);
Class<?> cls = Rs.getclass ();

The following is a one-time build agent
Subject Subject = (Subject) proxy.newproxyinstance (
Cls.getclassloader (), Cls.getinterfaces (), DS);
Subject.request ();
}
}

Example 2:

Copy Code code as follows:

Package com.langsin.dynamicproxy;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import java.util.List;
Import Java.util.Vector;
public class Vectorproxy implements Invocationhandler
{
Private Object proxyobj;
Public vectorproxy (Object obj) {
Proxyobj = obj;
}
public static object factory (object obj) {
Class<?> cls = Obj.getclass ();
Return Proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), New Vectorproxy (obj));
}
public object invoke (object proxy, Method method, object[] args) throws throwable{
System.out.println ("before calling" + method);
if (args!= null) {
for (int i = 0; i < args.length; i++) {
System.out.println (Args[i] + "");
}
}
Object object = Method.invoke (Proxyobj, args);
System.out.println ("After the Calling" + method);
return object;
}
@SuppressWarnings ("Unchecked")
public static void Main (string[] args) {
List<string> v = (list<string>) factory (new Vector<string> (10));
V.add ("New");
V.add ("York");
System.out.println (v);
V.remove (0);
System.out.println (v);
}
}

Instance 3,

Copy Code code as follows:

Package com.langsin.dynamicproxy;
public interface foo{
void Doaction ();
}
Package com.langsin.dynamicproxy;
public class Fooimpl implements foo{
Public Fooimpl () {
}
public void Doaction () {
System.out.println ("in Fooimp1.doaction ()");
}
}
Package com.langsin.dynamicproxy;
public class FOOIMPL2 implements foo{
Public FooImpl2 () {
}
public void Doaction () {
System.out.println ("in Fooimp2.doaction ()");
}
}
Package com.langsin.dynamicproxy;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
public class Commoninvocationhandler implements invocationhandler{
Dynamically executing an object that requires a callback
Private Object target;
Support for the construction of child injection
Public Commoninvocationhandler () {
}
Support for the construction of child injection
Public Commoninvocationhandler (Object target) {
Settarget (target);
}
/**
*
* Injection by Setter method
*
* @param target
*
*/
public void Settarget (Object target) {
This.target = target;
}
/**
*
* Invokes method methods specified in proxy and passes in the argument list args
*
* @param proxy
* The type of the proxy class, such as the proxy interface defining the corresponding method
*
* @param method
* Method of being represented
*
* @param args
* Invoke parameters of the proxy method
*
* @return
*
* @throws java.lang.Throwable
*
*/
public object invoke (object proxy, Method method, object[] args) throws throwable{
Return Method.invoke (target, args);
}
}
Package com.langsin.dynamicproxy;
Import Java.lang.reflect.Proxy;
public class demo{
public static void Main (string[] args) {
1. Universal Dynamic Proxy implementation
Commoninvocationhandler handler = new Commoninvocationhandler ();
Foo F;
2. Interface Implementation 1
Handler.settarget (New Fooimpl ());
Method Parameter Description: proxy class, proxy class implementation of the interface list, proxy class of the processor
association proxy class, proxy class interface method, processor, when the interface method in the proxy class is invoked, the Invoke method is automatically distributed to the processor
If the proxy class does not implement the specified interface list, an illegal parameter exception is thrown
f = (Foo) proxy.newproxyinstance (Foo.class.getClassLoader (),
New class[] {Foo.class},
handler);
F.doaction ();
3. Interface Implementation 2
Handler.settarget (New FooImpl2 ());
f = (Foo) proxy.newproxyinstance (Foo.class.getClassLoader (),
New class[] {Foo.class},
handler);
F.doaction ();
}
}

Because I have limited literary talent, so most of the content is code, but also please understand ^_^

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.