Is it possible to override a method at runtime?

三世轮回 提交于 2019-12-04 03:08:47

问题


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


回答1:


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




回答2:


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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/8273685/is-it-possible-to-override-a-method-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!