Home Java javaTutorial Detailed explanation of java dynamic proxy mode

Detailed explanation of java dynamic proxy mode

Feb 07, 2017 pm 01:31 PM

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();
}
Copy after login

2.2. DaoImpl class implementation class

package javaproxy;
  
public class DaoImpl implements Dao{
  
 @Override
 public void save() {
  System.out.println("执行一个保存方法。。。。。。。。。。。。");
    
 }
  
}
Copy after login

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;
 }
  
}
Copy after login

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();
  
 }
}
Copy after login

2. 5. Result

Detailed explanation of java dynamic proxy mode

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;
 }
 
}
Copy after login

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();
  
 }
}
Copy after login

3.3. Result

Detailed explanation of java dynamic proxy mode

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles