Proxy mode provides a proxy for other objects to control access to this object, mediations, which can remove feature services or add additional services 1. Common agents
Remote agents: provide local area network representative objects for different geographic objects
Virtual Proxy: Create a delay when you need to defer a resource-intensive object for real time
Protection agent: permission control
Smart Referral Agent: provides additional services
static Proxy: the proxy and the Proxied object are determined before the agent. They all implement the same interface or the same abstract class
2. Dynamic Agent Implementation principle
Implementation function: Returns the proxy object through the newproxyinstance of proxy
<1> declare a section of source code
<2> Compile source (JDK complier API), Generate new Class (proxy class)
<3> this type of load into memory, resulting in a new object (proxy object)
<4>return proxy Object
<5> Call Order
Dynamically generated according to the parameters passed in by Proxy.newinstance (). Class--
Returns the proxy class-and then uses the interface to receive the returned reference--method call
3. Source Code Analysis
Proxy static method Newproxyinstance
public static Object newProxyInstance(ClassLoader loader, Class<?>[]interfaces,InvocationHandler h) throws IllegalArgumentException { // 检查 h 不为空,否则抛异常if (h == null) { throw new NullPointerException(); } // 获得与指定类装载器和一组接口相关的代理类类型对象Class cl = getProxyClass(loader, interfaces); // 通过反射获取构造函数对象并生成代理类实例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 new InternalError(e.toString()); } catch (InstantiationException e) { throw new InternalError(e.toString()); } catch (InvocationTargetException e) { throw new InternalError(e.toString()); } }
The Getproxyclass method of the class proxy calls Proxygenerator's Generateproxyclass method to produce the binary data proxysubject.class:
public static byte[] generateProxyClass(final String name, Class[] interfaces)
We can import Sun.misc.ProxyGenerator, call the Generateproxyclass method to produce binary data, then write to the file, and finally through the Anti-compilation tool to see the internal implementation principle. Newproxyinstance of Proxysubject.java proxy static method after anti-compilation
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 undeclaredthrowableexception (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 (this, M3, null); Return } catch (Error _ex) {} catch (Throwable throwable) {throw new Undeclaredthrowableexception (Throwable); }} public final String toString () {try {return (String) Super.h.invoke (this, M2, null); } catch (Error _ex) {} catch (Throwable throwable) {throw new undeclaredthrowableexception (Throwable); }} static{try {m1 = Class.forName ("Java.lang.Object"). GetMethod ("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 (Nosuchmethodexception.getmessage ( )); } catch (ClassNotFoundException classnotfoundexception) {throw new Noclassdeffounderror (classnotfoundexception.getme Ssage ()); } } }
Proxygenerator internal is how to generate class binary data, you can refer to the source code.
Private byte[] Generateclassfile () {/* * Record that proxy methods is needed for the hashcode, equals, * and ToString methods of Java.lang.Object. This is do before * the methods from the proxy interfaces So, the methods from * Java.lang.Object take prece Dence 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 on Es 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 that the methods ' return types AR E compatible. */For (list<proxymethod> sigmethods:proxyMethods.values ()) {checkreturntypes (sigmethods); }/* ============================================================ * Step 2:assemble FieldInfo and MethodInfo Stru CTS 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 F Ield for method ' s method Object Fields.Add (New FieldInfo (Pm.methodfieldname, "Ljava/lang/reflect/method;", ACC_ PRIVATE | acc_static)); Generate code for Proxy method 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 constant pool indexes is reserved for the * following items before starting to write the final class F Ile. */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 is about to write the final Constan T pool table. */cp.setreadonly (); Bytearrayoutputstream bout = new Bytearrayoutputstream (); DataOutputStream dout = new DataOutputStream (bout); try {/* * Write all the items of the "classfile" structure. * See 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 ())); }//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 E Xception "); } return Bout.tobytearray ();
Java Dynamic Proxy