Using the LibCustom library, you can override any function at runtime. This is especially useful in tests where you have external dependencies that you cannot easily mock. Also useful when your codebase is not very modular and there are parts of the logic that calls other methods that you want to override with mocks.

First add LibCustom library to your pom.xml:

<dependency>
  <groupId>io.github.jleblanc64</groupId>
  <artifactId>lib-custom</artifactId>
  <version>1.0.7</version>
</dependency>

Say you have a class A, with a method add:

class A {

  static int add(int a, int b) {
    return a + b;
  }
}

As is, the method returns A.add(2,3) = 5. Let’s say that we want to override add with multiply at runtime:

LibCustom.override(A.class, "add", args -> {
  var a = (int) args[0];
  var b = (int) args[1];
  return a * b;
});

LibCustom.load();

Now, the method returns A.add(2,3) = 6.

Find the full working code in my Github repo


<
Blog Archive
Archive of all previous blog posts
>
Next Post
Use Vavr List and Option with Hibernate 6