This article organizes knowledge points on java dynamic proxy. The specific content is as follows
1. JAVA dynamic proxy (more official statement)
The proxy mode is a commonly used java design pattern, and its characteristic is proxy The class has the same interface as the delegate class. The proxy class is mainly responsible for preprocessing messages for the delegate class, filtering messages, forwarding messages to the delegate class, and processing messages afterwards. There is usually an association between a proxy class and a delegate class. An object of a proxy class is associated with an object of a delegate class. The object of the proxy class itself does not actually implement the service, but by calling the relevant methods of the object of the delegate class. Provide specific services.
According to the creation period of the agent, the agent class can be divided into two types.
Static proxy: Created by programmers or automatically generated by specific tools, and then compiled. Before the program is run, the .class file of the proxy class already exists.
Dynamic proxy: Dynamically created using the reflection mechanism when the program is running.
2. Dynamic proxy implementation
java.lang.reflect.Proxy,
Proxy provides static methods for creating dynamic proxy classes and instances.
newProxyInstance()
Returns a proxy class instance of the specified interface, which can assign method calls to the specified call handler.
2.1. Dao interface (providing simulated data access layer interface)
package javaproxy; /* * 定义一个数据访问层接口 */ public interface Dao { //模拟数据保存 public void save(); }
2.2. DaoImpl class implementation class
package javaproxy; public class DaoImpl implements Dao{ @Override public void save() { System.out.println("执行一个保存方法。。。。。。。。。。。。"); } }
2.3. Agent processing class
package javaproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class DaoHandler implements InvocationHandler{ private Object obj; public DaoHandler(Object obj) { this.obj=obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("do something before method");//这里模拟AOP的前置方法 Object ret = method.invoke(this.obj, args); System.out.println("do something after method");//这里模拟AOP的后置方法 return ret; } }
2.4. Client call
package javaproxy; import java.lang.reflect.Proxy; public class Client { public static void main(String[] args) { // 元对象(被代理对象) DaoImpl daoImpl = new DaoImpl(); // 业务代理类 DaoHandler daoHandler=new DaoHandler(daoImpl); Dao dao=(Dao) Proxy.newProxyInstance(daoImpl .getClass().getClassLoader(), daoImpl.getClass() .getInterfaces(), daoHandler); dao.save(); } }
2. 5. Result
3 . Simulate the proxy implementation in Mybatis
3.1. MapperProxy class
package javaproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class MapperProxy implements InvocationHandler { @SuppressWarnings("unchecked") /* * 这里通过静态方法得到实现类的对象 * * @param:接口 * * @param:用sqlsession执行方法 * * @return: 返回代理对像 */ public static <T> T newMapperProxy(Class<T> mapperInterface, Object sqlSession) { ClassLoader classLoader = mapperInterface.getClassLoader(); Class<?>[] interfaces = new Class[] { mapperInterface }; MapperProxy proxy = new MapperProxy(); return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy); } /* * (non-Javadoc) * * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[]) * * @param:代理对象 * * @param:方法通过方法名字找到对应的方法 * * @param:通过方法传入对象找到对应的传递参数映射 * * @return:返回执行后的参数对象 */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 这里通过方法名字以及参数通过解析对应的mapper来执行对应的操作 System.out.println("在这里执行实际方法"); return null; } }
3.2. Client
package javaproxy; import java.lang.reflect.Proxy; public class Client { public static void main(String[] args) { Dao dao=MapperProxy.newMapperProxy(Dao.class, null); dao.save(); } }
3.3. Result
The above are examples of using JDK dynamic proxy. I hope it will be helpful for everyone to learn java programming.
For more detailed articles related to java dynamic proxy mode, please pay attention to the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
