Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with SpringCloud:

>> Join Pro and download theeBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockitolibrary makes it easy to writeclean and intuitive unittests for your Java code.

Get started with mocking and improve your application testsusing ourMockito guide:

Download theeBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky processwith manypotential pitfalls. A solid grasp of thefundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications withourJava Concurrency guide:

>>Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the SpringWebFlux module, which has been improved upon ever since. Getstarted with the Reactor project basics andreactive programmingin Spring Boot:

>> Join Pro anddownload the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download theE-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download theE-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore theeBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through theLearnSpring course:

>> LEARNSPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building afullREST API with the framework:

>>The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advancedfunctionality within the Core to the deep OAuth support in theframework.

I built the security material astwo full courses - Core andOAuth, to get practical with these more complex scenarios. Weexplore when and how to use each feature andcode through it onthe backing project.

You can explore the course here:

>> Learn SpringSecurity

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle thecomplexity ofJPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided referencecourse:

>> CHECK OUT THECOURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure thatyour application is usable for everyone and meetsaccessibility standards that are required in many countries.

By automating these tests, teams canquickly detectissues related to screen reader compatibility, keyboardnavigation, color contrast, and other aspects that could pose abarrier to using the software effectively for people withdisabilities.

Learn how to automate accessibility testing with Selenium andtheLambdaTest cloud-based testing platform that letsdevelopers and testers perform accessibility automation on over3000+ real environments:

Automated Accessibility TestingWith Selenium

1. Introduction

This article is aboutJava’s dynamic proxies – which is one of the primary proxy mechanisms available to us in the language.

Simply put, proxies are fronts or wrappers that pass function invocation through their own facilities (usually onto real methods) – potentially adding some functionality.

Dynamic proxies allow one single class with one single method to service multiple method calls to arbitrary classes with an arbitrary number of methods. A dynamic proxy can be thought of as a kind ofFacade, but one that can pretend to be an implementation of any interface. Under the cover,it routes all method invocations to a single handler – theinvoke() method.

While it’s not a tool meant for everyday programming tasks, dynamic proxies can be quite useful for framework writers. It may also be used in those cases where concrete class implementations won’t be known until run-time.

This feature is built into the standard JDK, hence no additional dependencies are required.

2. Invocation Handler

Let us build a simple proxy that doesn’t actually do anything except printing what method was requested to be invoked and return a hard-coded number.

First, we need to create a subtype ofjava.lang.reflect.InvocationHandler:

public class DynamicInvocationHandler implements InvocationHandler {    private static Logger LOGGER = LoggerFactory.getLogger(      DynamicInvocationHandler.class);    @Override    public Object invoke(Object proxy, Method method, Object[] args)       throws Throwable {        LOGGER.info("Invoked method: {}", method.getName());        return 42;    }}

Here we’ve defined a simple proxy that logs which method was invoked and returns 42.

3. Creating Proxy Instance

A proxy instance serviced by the invocation handler we have just defined is created via a factory method call on thejava.lang.reflect.Proxy class:

Map proxyInstance = (Map) Proxy.newProxyInstance(  DynamicProxyTest.class.getClassLoader(),   new Class[] { Map.class },   new DynamicInvocationHandler());

Once we have a proxy instance we can invoke its interface methods as normal:

proxyInstance.put("hello", "world");

As expected a message aboutput() method being invoked is printed out in the log file.

4. Invocation Handler via Lambda Expressions

SinceInvocationHandler is a functional interface, it is possible to define the handler inline using lambda expression:

Map proxyInstance = (Map) Proxy.newProxyInstance(  DynamicProxyTest.class.getClassLoader(),   new Class[] { Map.class },   (proxy, method, methodArgs) -> {    if (method.getName().equals("get")) {        return 42;    } else {        throw new UnsupportedOperationException(          "Unsupported method: " + method.getName());    }});

Here, we defined a handler that returns 42 for all get operations and throwsUnsupportedOperationException for everything else.

It’s invoked in the exactly the same way:

(int) proxyInstance.get("hello"); // 42proxyInstance.put("hello", "world"); // exception

5. Timing Dynamic Proxy Example

Let’s examine one potential real-world scenario for dynamic proxies.

Suppose we want to record how long our functions take to execute. To this extent, we first define a handler capable of wrapping the “real” object, tracking timing information and reflective invocation:

public class TimingDynamicInvocationHandler implements InvocationHandler {    private static Logger LOGGER = LoggerFactory.getLogger(      TimingDynamicInvocationHandler.class);        private final Map<String, Method> methods = new HashMap<>();    private Object target;    public TimingDynamicInvocationHandler(Object target) {        this.target = target;        for(Method method: target.getClass().getDeclaredMethods()) {            this.methods.put(method.getName(), method);        }    }    @Override    public Object invoke(Object proxy, Method method, Object[] args)       throws Throwable {        long start = System.nanoTime();        Object result = methods.get(method.getName()).invoke(target, args);        long elapsed = System.nanoTime() - start;        LOGGER.info("Executing {} finished in {} ns", method.getName(),           elapsed);        return result;    }}

Subsequently, this proxy can be used on various object types:

Map mapProxyInstance = (Map) Proxy.newProxyInstance(  DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class },   new TimingDynamicInvocationHandler(new HashMap<>()));mapProxyInstance.put("hello", "world");CharSequence csProxyInstance = (CharSequence) Proxy.newProxyInstance(  DynamicProxyTest.class.getClassLoader(),   new Class[] { CharSequence.class },   new TimingDynamicInvocationHandler("Hello World"));csProxyInstance.length()

Here, we have proxied a map and a char sequence (String).

Invocations of the proxy methods will delegate to the wrapped object as well as produce logging statements:

Executing put finished in 19153 ns Executing get finished in 8891 ns Executing charAt finished in 11152 ns Executing length finished in 10087 ns

6. Conclusion

In this quick tutorial, we have examined Java’s dynamic proxies as well as some of its possible usages.

The code backing this article is available on GitHub. Once you'relogged in as aBaeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutelyNo-Ads as well asfinally withDark Mode, for a clean learning experience:

>> Explore a cleanBaeldung

Once the early-adopter seats are all used,the price will goup and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

TheApache HTTP Client is a very robust library, suitablefor both simple and advanced use cases whentesting HTTPendpoints. Check out our guide covering basic request andresponse handling, as well as security, cookies, timeouts, andmore:

>> Downloadthe eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky processwith manypotential pitfalls. A solid grasp of thefundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications withourJava Concurrency guide:

>>Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring,through theLearn Spring course:

>> CHECK OUTTHE COURSE

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring,through theLearn Spring course:

>> CHECK OUT THECOURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
Do JSON right with Jackson - book cover
Do JSON right with Jackson - icon
Do JSON right with Jackson
Download the E-book