简体   繁体   English

是否可以在运行时覆盖方法?

[英]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? 即使它需要从该实例动态创建子类?

With plain Java, no. 用普通的Java,没有。

With ByteBuddy (preferred), asm , cglib or aspectj , yes. 使用ByteBuddy (首选), asmcglibaspectj ,是的。

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). 在普通的Java中,在这种情况下要做的事情是创建一个基于接口的代理来处理方法调用并委托给原始对象(或不是)。

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 如果要从代码中查找动态编译​​,可以按照这些说明进行操作

As others said, no, you can't override a method at runtime. 正如其他人所说,不,你不能在运行时覆盖一个方法。 However, starting with Java 8 you can take the functional approach. 但是,从Java 8开始,您可以采用功能方法。 Function is a functional interface that allows you to treat functions as reference types. Function是一个功能接口,允许您将函数视为引用类型。 This means that you can create several ones and switch between them (dynamically) a-la strategy pattern. 这意味着您可以创建多个并在它们之间切换(动态)a-la策略模式。

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 11
9 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. 我不知道你打算在什么情况和设计中覆盖,但关键是你要替换方法的行为,这就是重写的行为。

I think it not possible with simple Java. 我认为简单的Java不可能。 With reflection and/or cglib probally you can do it. 有了反射和/或cglib,你可以做到。

Look at these links: 看看这些链接:
http://www.rgagnon.com/javadetails/java-0039.html http://www.rgagnon.com/javadetails/java-0039.html
http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM