This article mainly introduces the relevant information on the implementation and application of Java dynamic proxy in detail. I hope that through this article, everyone can understand and master the use of Java dynamic proxy. Friends in need can refer to it
Detailed explanation of the implementation and application of Java dynamic proxy
Java dynamic proxy is actually not commonly used to write daily business code, but it is very common and important to use the RPC framework client at the framework layer. The core idea of spring and the implementation of the underlying principles of aop use java's dynamic proxy technology.
Using a proxy can realize remote calling of objects and implementation of aop.
The implementation of Java's dynamic proxy mainly relies on InvoctionHandler (interface) and Proxy (class).
The following is an example
The agent implemented generally needs an interface
##
package com.yasin.ProxyLearn; public interface IStudy { public void learn(); public String getKonwledge(); }
package com.yasin.ProxyLearn; public class Study implements IStudy{ public void learn() { System.out.println("我要开始学习了!"); } public String getKonwledge() { return "Java真的强"; } }
package com.yasin.ProxyLearn; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class StudyProxy implements InvocationHandler{ //真实要被代理的对象 private Object study; public StudyProxy(Object study){ this.study=study; } /** * 当被代理对象执行自己的方法时,便会执行这个方法 */ public Object invoke(Object object, Method method, Object[] args) throws Throwable { Object obj=null; System.out.println("代理执行前我可以执行一些操作"); //执行被代理对象的方法 obj = method.invoke(study, args); System.out.println("代理执行后我还可以执行一些操作"); return obj; } }
package com.yasin.JavaLearn; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; import com.yasin.ProxyLearn.IStudy; import com.yasin.ProxyLearn.Study; import com.yasin.ProxyLearn.StudyProxy; /** * Hello world! * */ public class App { public static void main(String[] args) { IStudy study = new Study(); InvocationHandler handler = new StudyProxy(study); IStudy proxyStudy =(IStudy)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {IStudy.class}, handler); proxyStudy.learn(); System.out.println(proxyStudy.getKonwledge()); } }
The above is the detailed content of Detailed explanation of the application of dynamic proxy in Java. For more information, please follow other related articles on the PHP Chinese website!