Skip to main content

Overview

ActiveJ Codegen is an efficient Java code generator with a streamlined and simple API. It is built on top of ObjectWeb ASM and has zero-overhead performance. ActiveJ Codegen is widely used in ActiveJ Serializer, making it the fastest JVM-based serializer in the world). ActiveJ Codegen is one of the ActiveJ technologies, but has minimal third-party dependencies and can be used as a stand-alone component.

Why ActiveJ Codegen?

  • Utilizes ASM library for code generation and manipulation
  • Provides a concise Expressions API that provides a Lisp-like DSL for describing new classes
  • Supports caching of generated classes
  • Suitable for dynamic class generation based on runtime parameters (e.g. query processing)
  • Supports relational algebra operations for individual items: aggregate functions, predicates, ordering, group-by, etc.
  • Features automatic type inference
  • Zero-overhead performance
  • Built-in in-memory caching as well as the ability to use a persistent bytecode cache
  • Support for Records (heterogeneous data containers)

Code generation

Suppose we want to create a class that implements the Person interface.

public interface Greeter {
void sayHello();
}

A generated class should simply output "Hello World" message when the sayHello() method is called.

public class WorldGreeter implements Greeter {
@Override
public void sayHello() {
System.out.println("Hello World");
}
}

To generate such a class programmatically we need use the ClassGenerator class to define how a class should be created. We also need to use the DefiningClassLoader to actually define a new class.

DefiningClassLoader classLoader = DefiningClassLoader.create();

Class<Greeter> greeterClass = ClassGenerator.builder(Greeter.class)
.withMethod("sayHello",
call(staticField(System.class, "out"), "println", value("Hello world")))
.build()
.generateClass(classLoader);

Notice the call(staticField(System.class, "out"), "println", value("Hello world")) expression.

This is how Expressions DSL looks like. First, we access static field out of System class. Then we call println() method on it, passing value "Hello world" as an argument. This is equivalent to a System.out.println("Hello world)

When a new instance of this class is created and the sayHello() method is called, the output is "Hello world" as expected.

Greeter greeter = greeterClass.getDeclaredConstructor().newInstance();
greeter.sayHello(); // prints "Hello world" to stdout

This is merely a hint of what ActiveJ Codegen is capable of. For more information, please refer to examples or internal documentation.

Add ActiveJ Codegen to your project

You can add ActiveJ Codegen to your project by importing its Maven repository. These docs cover the most recent release of ActiveJ Codegen v6.0-beta2 (see on Github or Maven).