Design Mode-dynamic proxy

Source: Internet
Author: User

I. Understanding:

The proxy mode is a common java design mode. It features that the proxy class has the same interface as 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 agent creation period, the agent class can be divided into two types.
Static Proxy: the source code is automatically generated by the programmer or a specific tool, and then compiled. Before running the program, the. class file of the proxy class already exists.
Dynamic Proxy: a dynamic proxy is created using the reflection mechanism when the program is running.

2. Simulate jdk dynamic proxy

Code

// Call class

Package com. d12321.proxy; import java. lang. reflect. method; public class TankLogProxy implements com. d12321.proxy. movable {com. d12321.proxy. invocationHander tank; public TankLogProxy (InvocationHander tank) {this. tank = tank;} @ Overridepublic void run () throws Exception {Method md = com. d12321.proxy. movable. class. getMethod ("run"); tank. invoke (this, md) ;}/// running result tank start .... tank move .... tank end ....

// Dynamic Proxy (generate Proxy instance)

Package com. d12321.proxy; import java. io. file; import java. io. fileWriter; import java. lang. reflect. constructor; import java. lang. reflect. method; import java.net. URL; import java.net. URLClassLoader; import javax. tools. javaCompiler; import javax. tools. standardJavaFileManager; import javax. tools. toolProvider; import javax. tools. javaCompiler. compilationTask; public class Proxy {public static Object newProxyInstance (Class inter, InvocationHander h) throws Exception {String rt = "\ n"; String moths = ""; method [] MS = inter. getMethods ();/* for (Method m: MS) {moths + = "@ Override" + rt + "public void" + m. getName () + "() {" + rt + "System. out. println (\ "tank start .... \ ");" + rt + "" + "tank. "+ m. getName () + "();" + rt + "System. out. println (\ "tank end .... \ ");" + rt + "}";} */for (Method m: MS) {moths + = "@ Override" + rt + "public void" + m. getName () + "() throws Exception {" + rt + "Method md =" + inter. getName () + ". class. getMethod (\ "" + m. getName () + "\"); "+ rt +" tank. invoke (this, md); "+ rt +"} ";} String str =" package com. d12321.proxy; "+ rt +" import java. lang. reflect. method; "+ rt +" public class TankLogProxy implements "+ inter. getName () + "{" + rt + "com. d12321.proxy. invocationHander tank; "+ rt +" public TankLogProxy (InvocationHander tank) {"+ rt +" this. tank = tank; "+ rt +"} "+ rt + moths + rt +"} "; // source code String filename = System. getProperty ("user. dir ") +"/src/com/d12321/proxy/TankLogProxy. java "; File f = new File (filename); FileWriter fw = new FileWriter (f); fw. write (str); fw. flush (); fw. close (); // compile JavaCompiler compiler = ToolProvider. getSystemJavaCompiler (); StandardJavaFileManager fileMgr = compiler. getStandardFileManager (null, null, null); Iterable units = fileMgr. getJavaFileObjects (filename); CompilationTask t = compiler. getTask (null, fileMgr, null, units); t. call (); fileMgr. close (); // loader to memory URL [] urls = new URL [] {new URL ("file:/" + System. getProperty ("user. dir ") +"/src/")}; URLClassLoader ul = new URLClassLoader (urls); Class c = ul. loadClass ("com. d12321.proxy. tankLogProxy "); // production object Constructor ctr = c. getConstructor (InvocationHander. class); Object m = ctr. newInstance (h); return m ;}}

// InvocationHandler interface, call the method of the reflection execution object, and add the logic to the Method

// Interface

package com.d12321.proxy;import java.lang.reflect.Method;public interface InvocationHander {public void invoke(Object o, Method m);}

// Class that implements the interface

package com.d12321.proxy;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class TimeInvocationHander implements InvocationHander {private Object t;public TimeInvocationHander(Object t) {super();this.t = t;}public Object getT() {return t;}public void setT(Object t) {this.t = t;}@Overridepublic void invoke(Object o, Method m) {System.out.println("tank start ....");try {m.invoke(t, new Object[]{});} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}System.out.println("tank end ....");}}

// The class for which the logic needs to be added

// Interface

package com.d12321.proxy;public interface movable {void run() throws Exception;//void move();}

// Class

package com.d12321.proxy;public class Tank implements movable{@Overridepublic void run() {System.out.println("Tank move ....");}}

Summary:

First, Tank is an instance that implements the movable interface, and a logical class needs to be added. TimeInvocationHandler is an instance that implements the InvocationHandler interface, in which Method m is used. the invoke (Object o,) method calls the m method to add logic to the method. The Proxy can generate any Object and add an instance class of the logic class, just like the dynamic Proxy in jdk.

650) this. width = 650; "title =" 360201308122300101.jpg" src = "http://www.bkjia.com/uploads/allimg/131228/1123593019-0.jpg"/>

Located inJava. lang. reflect. Proxy

Knowledge points used

1. java reflection mechanism and method execution

2. How does java get the compiler and compile objects?

3. How does java loader objects to memory?

4. How does java generate instance objects?

5. Get the current project path system. getProperty ("userr. dir ")

This article from the "meditation, growth" blog, please be sure to keep this source http://xiaodu1993.blog.51cto.com/5327660/1270768

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.