Agent design mode
Definition: Provides a proxy for other objects to control access to this object.
The structure of the proxy pattern is shown in the following illustration.
Dynamic proxy Use
The Java dynamic proxy mechanism realizes the design concept of Agent mode in a clever way.
Proxy Mode Sample Code
Public interface Subject
{public
void dosomething ();
}
public class Realsubject implements Subject
{public
void dosomething ()
{
System.out.println ("Call DoSomething () ");
}
}
public class Proxyhandler implements Invocationhandler
{
private Object proxied;
Public Proxyhandler (Object proxied)
{
this.proxied = proxied;
}
The public object invoke (object proxy, Method method, object[] args) throws Throwable
{
//Before you transfer a specific target object, you can perform some function processing c20/>//the method of transferring specific target objects return
method.invoke (proxied, args);
After you have transferred a specific target object, you can perform some function processing
}
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import Sun.misc.ProxyGenerator;
Import java.io.*; public class Dynamicproxy {public static void main (String args[]) {realsubject real = new REALSUBJ
ECT ();
Subject Proxysubject = (Subject) proxy.newproxyinstance (Subject.class.getClassLoader (), New Class[]{subject.class},
New Proxyhandler (real));
Proxysubject.dosomething ();
Write Proxysubject class binary data to File Createproxyclassfile ();
public static void Createproxyclassfile () {String name = ' Proxysubject ';
byte[] data = Proxygenerator.generateproxyclass (name, new class[] {subject.class});
try {fileoutputstream out = new FileOutputStream (name + ". Class");
Out.write (data);
Out.close ();
catch (Exception e) {e.printstacktrace (); }
}
}
Internal implementation of dynamic proxy
First, let's look at the main static variables of proxy implemented by the Code of class proxy.
Mapping table: Used to maintain class loader object to its corresponding proxy class cache
private static Map Loadertocache = new Weakhashmap ();
Tags: used to mark a dynamic proxy class being created
private static Object Pendinggenerationmarker = new Object ();
Synchronization table: Records the dynamic proxy class types that have been created, and are mainly judged by method Isproxyclass
private static Map proxyclasses = Collections.synchronizedmap ( New Weakhashmap ());
The associated call processor references
protected invocationhandler h;
The method of constructing proxy
Because the constructor is never called directly inside the proxy, private type means that no call
to private proxy () {}
//Because the constructor is never called directly inside the proxy, protected means that only subclasses can Call
Proxy static method Newproxyinstance
public static Object newproxyinstance (ClassLoader loader, Class<?>[]interfaces,invocationhandler h) throws illegalargumentexception {
//check h is not NULL, otherwise throw exception
if (h = = null) {
throw new NullPointerException ();
}
Gets the proxy class type Object classes
CL = getproxyclass (loader, interfaces) associated with the specified class loader and a set of interfaces;
Gets the constructor object through reflection and generates the proxy class instance
try {
constructor cons = Cl.getconstructor (constructorparams);
Return (Object) cons.newinstance (new object[] {h});
catch (Nosuchmethodexception e) {throw new Internalerror (e.tostring ());
} catch (Illegalaccessexception e) {throw n EW Internalerror (e.tostring ());
} catch (Instantiationexception e) {throw new Internalerror (e.tostring ());
\ catch (invocationtargetexception e) {th Row New Internalerror (e.tostring ());
}
}
The Getproxyclass method of class Proxy invokes the Proxygenerator Generateproxyclass method to produce proxysubject.class binary data:
public static byte[] Generateproxyclass (final String name, class[] interfaces)
We can import Sun.misc.ProxyGenerator, call the Generateproxyclass method to generate binary data, and then write to the file, and finally through the Decompile tool to view the internal implementation principle. The Proxysubject.java Proxy static method after compiling newproxyinstance
Import java.lang.reflect.*;
Public final class Proxysubject extends Proxy implements Subject {private static method M1;
private static method M0;
private static method M3;
private static method m2;
Public Proxysubject (Invocationhandler Invocationhandler) {super (Invocationhandler); Public final Boolean equals (Object obj) {try {return (Boolean) Super
. H.invoke (This, M1, new object[] {obj}). Booleanvalue (); catch (Error _ex) {} catch (Throwable throwable) {throw new Undeclaredth
Rowableexception (Throwable); Public final int hashcode () {try {return (Integer) super.h.
Invoke (this, M0, null)). Intvalue (); catch (Error _ex) {} catch (Throwable throwable) {
throw new Undeclaredthrowableexception (Throwable); } public final void dosomething () {try {Super.h.invoke.
M3, NULL);
Return catch (Error _ex) {} catch (Throwable throwable) {throw new Undeclaredth
Rowableexception (Throwable); } Public final String toString () {try {return (String) super.h
. Invoke (this, M2, null); catch (Error _ex) {} catch (Throwable throwable) {throw new Undeclaredth
Rowableexception (Throwable); } static {try {m1 = Class.forName ("Java.lang.Object"). Getmet
Hod ("equals", new class[] {class.forname ("Java.lang.Object")}); M0 = Class.forName ("Java.lang.Object"). GetMethod ("Hashcode", new Class[0]);
M3 = Class.forName ("Subject"). GetMethod ("DoSomething", new class[0);
M2 = Class.forName ("Java.lang.Object"). GetMethod ("ToString", new Class[0]); catch (Nosuchmethodexception nosuchmethodexception) {throw new Nosuchmethoderror (no
Suchmethodexception.getmessage ()); catch (ClassNotFoundException classnotfoundexception) {throw new Noclassdeffounderr
or (Classnotfoundexception.getmessage ()); }
}
}
The
Proxygenerator generates class binary data internally, and can refer to the source code.
Private byte[] Generateclassfile () {/* record this proxy methods are needed for the hashcode, equals, * And ToString methods of Java.lang.Object. This was done before * the methods from the ' Proxy interfaces so ' methods from * Java.lang.Object take pre
Cedence over duplicate methods in the * Proxy interfaces.
* * Addproxymethod (Hashcodemethod, Object.class);
Addproxymethod (Equalsmethod, Object.class);
Addproxymethod (Tostringmethod, Object.class); * * Now record all of the methods from the proxy interfaces, giving * earlier interfaces precedence over later
Ones with duplicate * methods.
* for (int i = 0; i < interfaces.length i++) {method[] methods = Interfaces[i].getmethods ();
for (int j = 0; J < Methods.length J + +) {Addproxymethod (methods[j], interfaces[i]); }/* For each set of proxy methods with the same signature, * Verify thatThe methods ' return types are compatible.
* For (list<proxymethod> sigmethods:proxyMethods.values ()) {checkreturntypes (sigmethods); }/* ============================================================ * step 2:assemble FieldInfo and MethodInfo St
Ructs for all of * fields and methods in the class we are generating.
* * try {methods.add (Generateconstructor ()); For (list<proxymethod> sigmethods:proxyMethods.values ()) {for (Proxymethod pm:sigmethods) {/ /Add static field for method Object Fields.Add (New FieldInfo (Pm.methodfieldname, "Ljava/lang /reflect/method; ", Acc_private |
acc_static));
Generate code for Proxy and add it Methods.add (Pm.generatemethod ());
} methods.add (Generatestaticinitializer ()); catch (IOException e) {throw new Internalerror ("Unexpected I/O Exception");
}/* ============================================================ * Step 3:write the final class file. */* Make sure that constant pool indexes are reserved for the * following items before starting to WR
ITE the final class file.
* * Cp.getclass (Dottoslash (className));
Cp.getclass (Superclassname);
for (int i = 0; i < interfaces.length i++) {Cp.getclass (Dottoslash (Interfaces[i].getname ())); } * * Disallow new constant pool additions beyond this point, since * we are about to write the final cons
Tant pool table.
* * CP.SETREADONLY ();
Bytearrayoutputstream bout = new Bytearrayoutputstream ();
DataOutputStream dout = new DataOutputStream (bout);
try {* * * Write all the items of the "classfile" structure.
* JVMS Section 4.1.
*///U4 magic;
Dout.writeint (0xCAFEBABE);
U2 minor_version; Dout.writEshort (classfile_minor_version);
U2 major_version;
Dout.writeshort (classfile_major_version); Cp.write (dout);
(write constant pool)//U2 access_flags; Dout.writeshort (Acc_public | acc_final |
Acc_super);
U2 This_class;
Dout.writeshort (Cp.getclass (Dottoslash (ClassName)));
U2 Super_class;
Dout.writeshort (Cp.getclass (superclassname));
U2 Interfaces_count;
Dout.writeshort (interfaces.length);
U2 Interfaces[interfaces_count]; for (int i = 0; i < interfaces.length i++) {dout.writeshort (Cp.getclass dottoslash (interfaces[i].g
Etname ()));
}//U2 fields_count;
Dout.writeshort (Fields.size ());
Field_info Fields[fields_count];
for (FieldInfo f:fields) {f.write (dout);
}//U2 methods_count; Dout.writeshort (Methods.size ());
Method_info Methods[methods_count];
for (MethodInfo m:methods) {m.write (dout);
}//U2 attributes_count; Dout.writeshort (0); (No Classfile attributes for proxy classes)} catch (IOException e) {throw new Internalerror ("unexpected
I/O Exception ");
return Bout.tobytearray ();
Summarize
A typical dynamic proxy creation object process can be divided into the following four steps:
1, through the implementation of Invocationhandler interface to create their own call processor Ivocationhandler handler = new Invocationhandlerimpl (...);
2. Create a dynamic proxy class by specifying the ClassLoader object and a set of interface for the proxy class
Class clazz = Proxy.getproxyclass (classloader,new class[]{...});
3, through the reflection mechanism to obtain the dynamic proxy class constructor, the parameter type is the calling processor interface type
Constructor constructor = Clazz.getconstructor (New Class[]{invocationhandler.class});
4. Create a proxy class instance through the constructor, at which point the calling processor object is passed in as a parameter
Interface Proxy = (Interface) constructor.newinstance (new object[) (handler));
To simplify the object creation process, the Newinstance method in the proxy class encapsulates the 2~4, and it takes only two steps to complete the creation of the proxy object.
The generated proxysubject inherits the proxy class from implementing the subject interface, the implemented subject method actually invokes the processor's Invoke method, and the Invoke method invokes the method of the proxy object using reflection (object result= Method.invoke (Proxied,args))
Ointment
Admittedly, Proxy has been beautifully designed, but there is a little bit of regret that it is still unable to get rid of the shackles that support the interface agent because its design is doomed to this regret. Recall the inherited graphs of dynamically generated proxy classes, which are already destined to have a common parent called proxy. The Java inheritance mechanism has doomed these dynamic proxy classes to be unable to implement dynamic proxies for class, because multiple inheritance is inherently impractical in Java. There are many reasons why people can deny the need for class proxies, but there are also reasons to believe that it is better to support class dynamic proxies. Interface and class division, this is not very obvious, but in Java to become so refined. If only from the declaration of the method and whether it is defined, there is a mixture of both, its name is called abstract class. The realization of the dynamic proxy of abstract class, believe also has its intrinsic value. In addition, there are some legacy classes that will never be the same as dynamic proxies because they do not implement any interfaces. So many, have to say is a small regret. However, imperfect is not equal to not great, greatness is a kind of essence, Java Dynamic Proxy is an example.