Override any Java method at runtime
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
:
Say you have a class A
, with a method add
:
As is, the method returns A.add(2,3) = 5
. Let’s say that we want to override add
with multiply
at runtime:
Now, the method returns A.add(2,3) = 6
.
Find the full working code in my Github repo