In the 9 years of running Baeldung, we've never been through anything like this pandemic

And, if making my courses more affordable for a while is going to help you stay in business, land a new job, make rent or be able to provide for your family - then it's well worth doing.

Effective immediately, all Baeldung courses are 33% off their normal prices!

You'll find all three courses in the menu, above.

In the 9 years of running Baeldung, we've never been through anything like this pandemic

And, if making my courses more affordable for a while is going to help you stay in business, land a new job, make rent or be able to provide for your family - then it's well worth doing.

Effective immediately, all Baeldung courses are 33% off their normal prices!

You'll find all three courses in the menu, above.

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.7.1</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.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() .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.

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