Is it possible to override a method at runtime?

Is there a way to override the method at runtime? even if this requires dynamically creating a subclass from this instance?

+8
java override
source share
5 answers

With plain Java, no.

With asm or cglib or aspectj , yes.

In simple Java, what you need to do in this situation is to create a proxy server based on an interface that processes the method call and delegates the original object (or not).

+7
source share

You can create an anonymous class that overrides the method and uses the strategic template to decide what to do.

If you are looking for dynamic compilation from code, you can follow these instructions.

+2
source share
0
source share

I think this is not possible with plain Java. With reflection and / or cglib, you can probably do this.

Check out these links:
http://www.rgagnon.com/javadetails/java-0039.html
http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html

0
source share

As others have said, no, you cannot override a method at runtime. However, starting with Java 8, you can take a functional approach. Function is a functional interface that allows you to treat functions as reference types. This means that you can create several of them and switch between them (dynamically) a-la 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:

eleven
nine

I don’t know under what circumstances and design you intend to override, but the fact is that you replace the behavior of the method, which does the override.

0
source share

All Articles