Dynamic Proxy Principles and Applications — In-depth Analysis and Practical Guide

1. Introduction

In software development, the Proxy Pattern is a common design pattern, especially in scenarios where there's a need to enhance, control, or isolate the target object. Dynamic Proxy, as an advanced form of the Proxy Pattern, has wide applications, such as API call interception, logging, and access control.

2. Basic Concepts of Dynamic Proxy

Dynamic Proxy is a technology that allows the runtime dynamic creation of proxy classes. The core idea is:

  • Dynamically create proxy objects without modifying the target object.

  • Intercept method calls via proxy objects and enhance functionality before and after the method invocation.

  • Applicable in scenarios such as access control, transaction management, logging, remote calls, etc.

Common dynamic proxy technologies include:

  • JDK Dynamic Proxy (based on Java Reflection)

  • CGLIB Dynamic Proxy (based on bytecode enhancement)

  • ASM, Javassist, and other low-level bytecode manipulation technologies

3. JDK Dynamic Proxy Implementation

JDK provides the java.lang.reflect.Proxy and InvocationHandler interfaces, which allow proxy objects to be created at runtime.

Implementation Steps

  1. The target class must implement an interface.

  2. Create an InvocationHandler to define the enhancement logic in the invoke method.

  3. Use Proxy.newProxyInstance() to generate the proxy object.

Example Code

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

// Target interface

interface Service {

void execute();

}

// Target implementation

class RealService implements Service {

public void execute() {

System.out.println("Executing real service logic");

}

}

// Proxy handler

class ServiceProxyHandler implements InvocationHandler {

private final Object target;

public ServiceProxyHandler(Object target) {

this.target = target;

}

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

System.out.println("Before method call");

Object result = method.invoke(target, args);

System.out.println("After method call");

return result;

}

}

// Testing Dynamic Proxy

public class JDKProxyExample {

public static void main(String[] args) {

Service realService = new RealService();

Service proxyInstance = (Service) Proxy.newProxyInstance(

realService.getClass().getClassLoader(),

realService.getClass().getInterfaces(),

new ServiceProxyHandler(realService));

proxyInstance.execute();

}

}

Suitable Scenarios

  • The target object must implement an interface.

  • Suitable for scenarios such as access control, logging, method monitoring, etc.

4. CGLIB Dynamic Proxy Implementation

CGLIB (Code Generation Library) uses bytecode enhancement technology, allowing proxying of regular classes (no interface required).

Implementation Steps

  1. The target class does not need to implement an interface.

  2. Create a MethodInterceptor to intercept method calls.

  3. Use CGLIB's Enhancer to generate the proxy object.

Example Code

import net.sf.cglib.proxy.Enhancer;

import net.sf.cglib.proxy.MethodInterceptor;

import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

// Target class (no interface required)

class RealService {

public void execute() {

System.out.println("Executing real service logic");

}

}

// Proxy class

class CglibProxy implements MethodInterceptor {

private final Object target;

public CglibProxy(Object target) {

this.target = target;

}

public Object createProxy() {

Enhancer enhancer = new Enhancer();

enhancer.setSuperclass(target.getClass());

enhancer.setCallback(this);

return enhancer.create();

}

@Override

public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

System.out.println("Before method call");

Object result = proxy.invokeSuper(obj, args);

System.out.println("After method call");

return result;

}

}

// Testing CGLIB Proxy

public class CglibProxyExample {

public static void main(String[] args) {

RealService realService = new RealService();

RealService proxy = (RealService) new CglibProxy(realService).createProxy();

proxy.execute();

}

}

Suitable Scenarios

  • Suitable for classes without implementing an interface.

  • Applicable in scenarios like Spring AOP, caching proxies, transaction management, etc.

5. Practical Applications of Dynamic Proxy

Dynamic proxy is widely used in fields like logging, monitoring, security, and network proxies. For example, in web scraping, market analysis, and data extraction, proxy IPs are used to bypass restrictions and obtain real data.

LuckData Proxy IP Application Examples

LuckData offers data center proxies, residential proxies, and dynamic residential proxies, applicable in scenarios such as SEO monitoring, market research, ad verification, web testing, and social media.

Python using LuckData Proxy

import requests

proxyip = "http://Account:Password@ahk.luckdata.io:Port"

url = "https://api.ip.cc"

proxies = {'http': proxyip, 'https': proxyip}

data = requests.get(url=url, proxies=proxies)

print(data.text)

Java using LuckData Proxy

OkHttpClient client = new OkHttpClient.Builder()

.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("ahk.luckdata.io", Port)))

.proxyAuthenticator((route, response) -> response.request().newBuilder()

.header("Proxy-Authorization", Credentials.basic("Account", "Password"))

.build())

.build();

Advantages of Proxy IPs

  • Bypass Geographical Restrictions: Choose from over 200 countries/regions IPs.

  • Enhanced Data Acquisition: Used in SEO, market research, brand protection, etc.

  • Secure and Reliable: 99.99% stability with unlimited concurrency.

6. Conclusion

Dynamic proxy is a very important technology in modern development, widely applied in access management, logging enhancement, remote calls, etc. At the same time, LuckData's proxy IP solution can help enterprises with market analysis, SEO monitoring, social media marketing, and assist in global business expansion.

If you wish to combine dynamic proxy technology with an efficient proxy IP solution, consider trying LuckData! https://luckdata.io/proxy/dynamic