Scala:在运行时替换方法 [英] Scala: replace method at runtime
问题描述
假设我有一堂课
class Original {
def originalMethod = 1
}
现在,假设我有一个实例
Now, let's say I have an instance of it
val instance = new Original
现在是否可以在运行时对 instance
做一些事情来用不同的方法替换 originalMethod
?(授予签名保持不变)
Is it now possible to do something to instance
at runtime to replace the originalMethod
with a different method? (granted the signature stays the same)
例如,现在当调用instance.originalMethod
时,下面的代码将被调用println("test");1
For example, now, when calling instance.originalMethod
the following code will be called println("test"); 1
编辑我无法调用 new Original
.我只有一个现有的实例,我必须修改它.
EDIT
I can't call new Original
. I just have an existing instance of it, which I have to modify.
编辑 2(@Aleksey Izmailov 回答)这是一个不错的解决方案,但并不是我正在寻找的.我更多地考虑测试 - 正常"编写一个类,而不将函数指定为变量而不是方法
EDIT 2 (@Aleksey Izmailov answer) This is a nice solution, but isn't exactly what I'm looking for. I'm thinking more in terms of testing - writing a class "normally", without specifying functions as variables rather than methods
附注.我在模仿 Mockito 间谍时偶然发现了这个问题
PS. I stumbled on this question when trying to mimic a Mockito spy
推荐答案
这在 JVM 上是不可能的——在 Java 或 Scala 中——不是你所要求的方式.
This isn't possible on the JVM — in either Java or Scala — not in the way that you're asking for.
参见例如在 Java 中,给定一个对象,是否可以覆盖其中一种方法?
使用 Scala 而不是 Java 不会让您获得额外的优势,因为类和方法在 Scala 中的工作原理与 Java 相同.(这样做是出于性能和互操作的原因.)
Being in Scala instead of Java doesn't gain you additional leverage, since the fundamentals of how classes and methods work in Scala are the same as Java's. (This was done for both performance and interop reasons.)
这篇关于Scala:在运行时替换方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!