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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built 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 can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built 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 can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free 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 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 – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
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 – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

The Java Class-File API was introduced in JEP-484 as part of Java 24. It aims to create an interface that allows class file processing without relying on the legacy JDK’s internal copy implementation of the ASM library.

In this tutorial, we’ll look at how to build class files from scratch and how to transform a class file into another using the Class-File API.

2. Core Class-File API Components

The Class-File has three core elements to generate and transform features that we’ll see later:

  • An element represents a part of the code, like a variable, an instruction, a method, or a class. Additionally, one element might contain other elements. For instance, a class element may contain method elements, which include variable or instruction elements.
  • Builders, such as method builders and code builders, are used to create each type of element.
  • A transform function can be used to transform elements into other elements using builders.

Let’s explore how these three components connect through practical examples in the following sections.

3. Generating a Class-File

In this section, we’ll see how to generate a class file using the MethodBuilder and CodeBuilder classes.

3.1. Demo Method

To illustrate class generation, let’s look at a simple code snippet that calculates an employee’s salary based on their function and base salary:

public double calculateAnnualBonus(double baseSalary, String role) {
    if (role.equals("sales")) {
        return baseSalary * 0.35;
    }

    if (role.equals("engineer")) {
        return baseSalary * 0.25;
    }

    return baseSalary * 0.15;
}

3.2. Using MethodBuilder and CodeBuilder

To generate a method with the same functionality as calculateAnnualBonus(), we can use the MethodBuilder and CodeBuilder classes. Hence, let’s first define the generate() method with a Consumer<MethodBuilder> that will be used to construct methods:

public static void generate() throws IOException {
    Consumer<MethodBuilder> calculateAnnualBonusBuilder = methodBuilder -> methodBuilder.withCode(codeBuilder -> {
        Label notSales = codeBuilder.newLabel();
        Label notEngineer = codeBuilder.newLabel();
        ClassDesc stringClass = ClassDesc.of("java.lang.String");

        // ...
    });
}

First, we define two Label objects that will be used later for jumping between conditional statements. Additionally, we’ve defined a ClassDesc constant that represents the String class file for later use.

Then, we can add the first part of our logic inside the calculateAnnualBonusBuilder‘s lambda expression:

codeBuilder.aload(3)
  .ldc("sales")
  .invokevirtual(stringClass, "equals", MethodTypeDesc.of(ClassDesc.of("Z"), stringClass))
  .ifeq(notSales)
  .dload(1)
  .ldc(0.35)
  .dmul()
  .dreturn()

Let’s look at each line of the above logic in detail:

  • We first start using aload(3) to load the role method parameter into a reference. Noticeably, the parameter of aload() is the slot number of the variable in the method arguments, where long and double take two slots. Thus, the first baseSalary argument is at slot 1, and role is at slot 3.
  • Then, we use ldc() to store the sales constant in the operand stack for the subsequent operations.
  • After that, we call invokevirtual() on the last operands from the stack, which are the constant “sales” and the role parameter. Furthermore, we invoke the equals() method of the String class stored in the stringClass variable to compare the operands. The ClassDesc.of(Z) part says that we expect a boolean as the return type of that method invocation.
  • We then call ifeq() passing the notSales label variable. That means the following instructions of the builder will run only if the previous boolean result of invokevirtual() returns true. Otherwise, the program should jump to the notSales binding that we’ll define later.
  • Finally, if the condition of ifReq() returns true, we load the baseSalary argument using dload(1). Then, we load the constant 0.35 to the operand stack and use dmul() to multiply the operands stored. Finally, we return the value using dreturn()

That first part covers the first if statement of the method we want to generate. Hence, to generate the second if statement, we can add more method calls to our codeBuilder(), after the dreturn() call:

  .labelBinding(notSales)
  .aload(3)
  .ldc("engineer")
  .invokevirtual(stringClass, "equals", MethodTypeDesc.of(ClassDesc.of("Z"), stringClass))
  .ifeq(notEngineer)
  .dload(1)
  .ldc(0.25)
  .dmul()
  .dreturn()

The labelBinding(notSales) runs if the ifeq(notSales) expression returns false. The other operations are similar to those we previously covered to handle the first if statement.

Finally, we can add the last part to cover the default value return:

  .labelBinding(notEngineer)
  .dload(1)
  .ldc(0.15)
  .dmul()
  .dreturn();

The same thing occurs with labeling branches, but now for the notEngineer label. That last part runs if ifeq(notEngineer) returns false.

Finally, to wrap up our generate() method, we need to define the ClassFile object and write it to a .class file:

var classBuilder = ClassFile.of()
  .build(ClassDesc.of("EmployeeSalaryCalculator"),
    cb - > cb.withMethod("calculateAnnualBonus", MethodTypeDesc.of(CD_double, CD_double, CD_String), 
      AccessFlag.PUBLIC.mask(), 
      calculateAnnualBonusBuilder));

Files.write(Path.of("EmployeeSalaryCalculator.class"), classBuilder);

We’ve used ClassFile.of().build() to instantiate a class file builder, and passed two arguments to it. The first is the class name wrapped inside the ClassDesc.of() call. The second is a ClassBuilder consumer that generates the class with the desired methods. For that, we used withMethod() passing the method name, the method signature, the access flag, and the method code builder defined previously.

Noticeably, we defined the method signature as MethodTypeDesc.of(CD_double, CD_double, CD_String), which means that the method generated returns a double, defined by the first parameter, and receives a double and a String parameter.

Then, we write the byte array stored in the classBuilder variable to a file using the Files writers.

4. Transforming a Class-File Into Another

Now, let’s say we want to copy all the contents of a class file into another. We can do that by using different transformations:

public static void transform() throws IOException {
    var basePath = Files.readAllBytes(Path.of("EmployeeSalaryCalculator.class"));

    CodeTransform codeTransform = ClassFileBuilder::accept;

    MethodTransform methodTransform = MethodTransform.transformingCode(codeTransform);
    ClassTransform classTransform = ClassTransform.transformingMethods(methodTransform);

    ClassFile classFile = ClassFile.of();
    byte[] transformedClass = classFile.transformClass(classFile.parse(basePath), classTransform);
    Files.write(Path.of("TransformedEmployeeSalaryCalculator.class"), transformedClass);
}

In the example above, we first read the class file we created in the previous section, EmployeeSalaryCalculator.

Then, we define a CodeTransform that accepts all CodeElements defined in the original class. Moreover, we create a MethodTransform using the codeTransform and a ClassTransform using the methodTransform. Such a composition makes it easy to generalize and reuse transformers for different purposes.

More customized code and method transforms could be defined using more explicit lambda expressions. For instance, we could define a custom MethodTransform using a lambda expression that only accepts methods with specific names:

MethodTransform methodTransform = (methodBuilder, methodElement) - > {
    if (methodElement.header().name().stringValue().equals("calculateAnnualBonus")) {
        methodBuilder.withCode(codeBuilder - > {
            for (var codeElement: methodElement.code()) {
                codeBuilder.accept(codeElement);
            }
        });
    }
};

In the case above, we first check if the method name is equal to the literal calculateAnnualBonus, using the header() and name() methods. If so, we use the methodBuilder to create a method with the exact instructions from the original class’ methodElement.

5. Conclusion

In this article, we looked at the details of creating classes from scratch and copying content from one class to another using the Class File API.

We examined examples of how to utilize various builders, transformers, and elements to create and transform classes at runtime.

As always, the source code is available over on GitHub.

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.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built 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 can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built 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 can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
Subscribe
Notify of
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments