Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override a method at runtime?

Is there anyway to override a method at run time? Even if it requires dynamically creating a subclass from that instance?

like image 705
Maxwell Dergosits Avatar asked Nov 25 '11 19:11

Maxwell Dergosits


People also ask

Is overriding a runtime process?

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.

Can an object's method be overridden with a custom implementation at runtime?

As others said, no, you can't override a method at runtime.

Why is method overriding resolved 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.

Which methods Cannot be override?

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.


2 Answers

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.

like image 169
user1803551 Avatar answered Sep 27 '22 16:09

user1803551


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).

like image 30
Sean Patrick Floyd Avatar answered Sep 27 '22 15:09

Sean Patrick Floyd