Is there anyway to override a method at run time? Even if it requires dynamically creating a subclass from that instance?
-
1Why? What are you trying to do? – SLaks Nov 25 '11 at 19:59
-
@Maxwell what is your reasoning for wanting to do this? Are you only able to determine the method details at run-time? – Matthew Cox Nov 25 '11 at 19:59
-
http://cglib.sourceforge.net/apidocs/net/sf/cglib/Enhancer.html ? – Roman Pokrovskij Nov 11 '18 at 13:17
-
5Here is a reason you might want this: You're using a jar/maven library. It works great, but one method is bad.. its buried in the code. Overriding isn't an option. It would be nice to replace one method with another that corrects the behavior. – bhlowe Jul 28 '19 at 14:37
4 Answers
With plain Java, no.
With ByteBuddy(preferred), asm, cglib or aspectj, yes.
In plain Java, the thing to do in a situation like that is to create an interface-based proxy that handles the method invocation and delegates to the original object (or not).

- 292,901
- 67
- 465
- 588
You could create an anonymous class that overrides the method and uses the strategy pattern to decide what to do.
If you are looking for dynamic compilation from code, you can follow these instructions

- 1,517
- 1
- 17
- 35
-
Btw, I used dynamic compilation to implement a scripted testing framework in .NET. I read a C# script and composed a class : "public class Test { public void Method() {" + userScript + "}}". Then I just build the whole thing and called "Test.Method" using reflection just like in the link I sent. – Kevin Coulombe Nov 25 '11 at 20:10
As others said, no, you can't override a method at runtime. However, starting with Java 8 you can take the functional approach. Function
is a functional interface that allows you to treat functions as reference types. This means that you can create several ones and switch between them (dynamically) a-la strategy pattern.
Let's look at an example:
public class Example {
Function<Integer, Integer> calculateFuntion;
public Example() {
calculateFuntion = input -> input + 1;
System.out.println(calculate(10));
// all sorts of things happen
calculateFuntion = input -> input - 1;
System.out.println(calculate(10));
}
public int calculate(int input) {
return calculateFuntion.apply(input);
}
public static void main(String[] args) {
new Example();
}
}
Output:
11
9
I don't know under what circumstances and design you intend to override, but the point is that you replace the behavior of the method, which is what overriding does.

- 12,965
- 5
- 47
- 74
I think it not possible with simple Java. With reflection and/or cglib probally you can do it.
Look at these links:
http://www.rgagnon.com/javadetails/java-0039.html
http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html

- 2,088
- 1
- 21
- 22