Java-dynamic proxy
In static proxy, we get the proxy class first when calling the target class, because the proxy class uses the target class as a member variable and inherits the same interface as the target class, there are the same methods. Therefore, in the proxy class, you can call the method of the target class to insert special operations before and after the method of the target class.
However, static proxy has two disadvantages: 1. There are many proxy classes. Every time a target class is added, a proxy is required; 2. In the proxy class, it may be the same when we need to insert operations, which leads to code duplication.
Therefore, by introducing reflection, you can implement dynamic proxy to improve static proxy.
/*** @ ClassName: LogHandler * @ Description: used to create a proxy class * @ author paddy field * @ date 11:17:51 on January 1, December 8, 2015 */public class LogHandler implements InvocationHandler {private Object targetObject; public Object newProxyInstance (Object targetObj) implements this.tar getObject = targetObj;/** 1. Obtain classLoader * 2 of the class and obtain interface * 3 of the created class, class of the incoming callback invoke method **/return Proxy. newProxyInstance (targetObj. getClass (). getClassLoader (), targetObj. getClass (). getInterfaces (), this);}/** (non-Javadoc)
Title: invoke
Description:
** @ Param proxy ** @ param call method information ** @ param args: parameter array of the method ** @ return ** @ throws Throwable ** @ see java. lang. reflect. invocationHandler # invoke (java. lang. object, * java. lang. reflect. method, java. lang. object []) * // @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {for (int I = 0; I <args. length; I ++) {System. out. println (args [I]);} try {// call the method of the target class and return an object. If the method does not return a value, null method is returned. invoke (targetObject, args);} catch (Exception e) {e. printStackTrace (); throw e;} System. out. println (start ----- >>> + method. getName (); return method. getName ();}}
Example:
/* Dynamic proxy example */LogHandler logHandler = new LogHandler (); UserManager userManager = (UserManager) logHandler. newProxyInstance (new UserManagerImpl (); userManager. addUser (2343254, lhc );
We put the operations to be inserted before and after executing the called method in the target class in the callback function invoke method. When the proxy class calls the corresponding method, it will directly enter the invoke method here, using method, and the third invoke parameter can get the information of the called method.