If you’re working with Spring, check out "REST With Spring":


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:


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

compile net.bytebuddy:byte-buddy:1.7.1

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()
  .intercept(FixedValue.value("Hello World ByteBuddy!"))

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()

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

  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()
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:

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

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()
  .defineMethod("custom", String.class, Modifier.PUBLIC)
  .defineField("x", String.class, Modifier.PUBLIC)
    getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)

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

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:


The latest version can be found here.

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

new ByteBuddy()
  .intercept(FixedValue.value("Hello Foo Redefined"))
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.

And, as always, the complete code snippets for this tutorial can be found over on Github.

The new Certification Class of "REST With Spring" is finally out:


Leave a Reply

1 Comment on "A Guide to Byte Buddy"

Notify of
Sort by:   newest | oldest | most voted

Thanks for the article. However, method’s signature is not just a list of parameters’ types.