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

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

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

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

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

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

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

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

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

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

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

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

Do JSON right with Jackson

Download the E-book

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

Get the most out of the Apache HTTP Client

Download the E-book

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

Get Started with Apache Maven:

Download the E-book

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

Working on getting your persistence layer right with Spring?

Explore the eBook

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 the Learn Spring course:

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

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST 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 advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

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

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

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Simply put, ByteBuddy is a library for generating Java classes dynamically at run-time.

In this to-the-point article, we’re going to use the framework to manipulate existing classes, create new classes on demand, and even intercept method calls.

2. Dependencies

Let’s first add the dependency to our project. For Maven-based projects, we need to add this dependency to our pom.xml:

<dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
    <version>1.14.18</version>
</dependency>

For a Gradle-based project, we need to add the same artifact to our build.gradle file:

compile net.bytebuddy:byte-buddy:1.12.13

The latest version can be found on Maven Central.

3. Creating a Java Class at Runtime

Let’s start by creating a dynamic class by subclassing an existing class. We’ll have a look at the classic Hello World project.

In this example, we create a type (Class) that is a subclass of Object.class and override the toString() method:

DynamicType.Unloaded unloadedType = new ByteBuddy()
  .subclass(Object.class)
  .method(ElementMatchers.isToString())
  .intercept(FixedValue.value("Hello World ByteBuddy!"))
  .make();

What we just did was to create an instance of ByteBuddy. Then, we used the subclass() API to extend Object.class, and we selected the toString() of the super class (Object.class) using ElementMatchers.

Finally, with the intercept() method, we provided our implementation of toString() and return a fixed value.

The make() method triggers the generation of the new class.

At this point, our class is already created but not loaded into the JVM yet. It is represented by an instance of DynamicType.Unloaded, which is a binary form of the generated type.

Therefore, we need to load the generated class into the JVM before we can use it:

Class<?> dynamicType = unloadedType.load(getClass()
  .getClassLoader())
  .getLoaded();

Now, we can instantiate the dynamicType and invoke the toString() method on it:

assertEquals(
  dynamicType.newInstance().toString(), "Hello World ByteBuddy!");

Note that calling dynamicType.toString() will not work since that will only invoke the toString() implementation of ByteBuddy.class.

The newInstance() is a Java reflection method that creates a new instance of the type represented by this ByteBuddy object; in a way similar to using the new keyword with a no-arg constructor.

So far, we’ve only been able to override a method in the super class of our dynamic type and return fixed value of our own. In the next sections, we will look at defining our method with custom logic.

4. Method Delegation and Custom Logic

In our previous example, we return a fixed value from the toString() method.

In reality, applications require more complex logic than this. One effective way of facilitating and provisioning custom logic to dynamic types is the delegation of method calls.

Let’s create a dynamic type that subclasses Foo.class which has the sayHelloFoo() method:

public String sayHelloFoo() { 
    return "Hello in Foo!"; 
}

Furthermore, let’s create another class Bar with a static sayHelloBar() of the same signature and return type as sayHelloFoo():

public static String sayHelloBar() { 
    return "Holla in Bar!"; 
}

Now, let’s delegate all invocations of sayHelloFoo() to sayHelloBar() using ByteBuddy‘s DSL. This allows us to provide custom logic, written in pure Java, to our newly created class at runtime:

String r = new ByteBuddy()
  .subclass(Foo.class)
  .method(named("sayHelloFoo")
    .and(isDeclaredBy(Foo.class)
    .and(returns(String.class))))        
  .intercept(MethodDelegation.to(Bar.class))
  .make()
  .load(getClass().getClassLoader())
  .getLoaded()
  .newInstance()
  .sayHelloFoo();
        
assertEquals(r, Bar.sayHelloBar());

Invoking the sayHelloFoo() will invoke the sayHelloBar() accordingly.

How does ByteBuddy know which method in Bar.class to invoke? It picks a matching method according to the method signature, return type, method name, and annotations.

The sayHelloFoo() and sayHelloBar() methods do not have the same name, but they have the same method signature and return type.

If there is more than one invocable method in Bar.class with matching signature and return type, we can use @BindingPriority annotation to resolve the ambiguity.

@BindingPriority takes an integer argument – the higher the integer value, the higher the priority of calling the particular implementation. Thus, sayHelloBar() will be preferred over sayBar() in the code snippet below:

@BindingPriority(3)
public static String sayHelloBar() { 
    return "Holla in Bar!"; 
}

@BindingPriority(2)
public static String sayBar() { 
    return "bar"; 
}

5. Method and Field Definition

We have been able to override methods declared in the super class of our dynamic types. Let’s go further by adding a new method (and a field) to our class.

We will use Java reflection to invoke the dynamically created method:

Class<?> type = new ByteBuddy()
  .subclass(Object.class)
  .name("MyClassName")
  .defineMethod("custom", String.class, Modifier.PUBLIC)
  .intercept(MethodDelegation.to(Bar.class))
  .defineField("x", String.class, Modifier.PUBLIC)
  .make()
  .load(
    getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
  .getLoaded();

Method m = type.getDeclaredMethod("custom", null);
assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar());
assertNotNull(type.getDeclaredField("x"));

We created a class with the name MyClassName that is a subclass of Object.class. We then define a method, custom, that returns a String and has a public access modifier.

Just like we did in previous examples, we implemented our method by intercepting calls to it and delegating them to Bar.class that we created earlier in this tutorial.

6. Redefining an Existing Class

Although we have been working with dynamically created classes, we can work with already loaded classes as well. This can be done by redefining (or rebasing) existing classes and using ByteBuddyAgent to reload them into the JVM.

First, let’s add ByteBuddyAgent to our pom.xml:

<dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy-agent</artifactId>
    <version>1.7.1</version>
</dependency>

The latest version can be found here.

Now, let’s redefine the sayHelloFoo() method we created in Foo.class earlier:

ByteBuddyAgent.install();
new ByteBuddy()
  .redefine(Foo.class)
  .method(named("sayHelloFoo"))
  .intercept(FixedValue.value("Hello Foo Redefined"))
  .make()
  .load(
    Foo.class.getClassLoader(), 
    ClassReloadingStrategy.fromInstalledAgent());
  
Foo f = new Foo();
 
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");

7. Conclusion

In this elaborate guide, we’ve looked extensively into the capabilities of the ByteBuddy library and how to use it for efficient creation of dynamic classes.

Its documentation offers an in-depth explanation of the inner workings and other aspects of the library.

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

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

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

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

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

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

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java 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 a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and 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 the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

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

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)