Is there anyway to override a method at run time? Even if it requires dynamically creating a subclass from that instance?
Method overriding is the runtime polymorphism having the same method with same parameters or signature but associated withcompared, different classes. It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.
As others said, no, you can't override a method at runtime.
Method overriding uses the dynamic method dispatch technique to resolve the method call and decide whether to call a superclass or subclass method and this is done at runtime. Hence runtime polymorphism is also called dynamic polymorphism or late binding.
Static methods can not be overridden We can not override the static methods in a derived class because static methods are linked with the class, not with the object. It means when we call a static method then JVM does not pass this reference to it as it does for all non-static methods.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With