调用不同对象的闭包? [英] Calling closure on different object?
问题描述
假设我有这个类:
class MyClass {
int myInt
MyClass(myInt) {
this.myInt = myInt
}
def myMethod() {
print this.myInt
}
}
和某处:
def myClass1 = new MyClass(1)
def myMethodClosure = myClass1.&myMethod
def myClass2 = new MyClass(2)
现在如果我调用 myMethodClosure()
,它会调用 myMethod )在
myClass1
实例将打印1.我想要的是调用相同的 myMethodClosure
但是在不同的实例上,在这种情况下在 myClass2
,所以它可以打印2.这是可能吗?
Now if I call myMethodClosure()
it will call myMethod()
on myClass1
instance which will print 1. What I want is to call the same myMethodClosure
but on a different instance, in this case on myClass2
so it can print 2. Is this possible?
我尝试使用 setDelegate()
,但它不工作。我还看到在闭包类中有字段 thisObject
,但它没有setter,只有一个getter。
I have tried using setDelegate()
, but it does not work. I have also seen that there is field thisObject
inside the closure class, but it does not have a setter, only a getter.
推荐答案
有两种方法添加到Groovy以帮助Closures序列化, dehydrate
和 rehydrate
。基本上,他们剥离(并重构)一个Closure的所有者
, thisObject
和委托
。在此示例中,您可以执行:
There were two methods added to Groovy to aid serialization of Closures, dehydrate
and rehydrate
. Basically, they strip (and reconstruct) a Closure's owner
, thisObject
and delegate
. In this example, you could do:
myMethodClosure.rehydrate( myClass2, myClass2, myClass2 )()
然而,要获得输出 2
我会警惕这样做,因为这不是该方法的目的,可能会有严重的不可预见的后果。
To get the output 2
, however I'd be wary about doing this as it is not what the method was intended for and there could be serious unforeseen consequences.
更好的解决方案可能是写一个工厂方法,为 MyClass
的给定实例获取方法引用。可能有其他更好的解决方案,但这取决于你所处的情况(我怀疑这个问题中的例子没有显示)
A better solution would probably be to write a factory method that gets a method reference for the given instance of MyClass
. There may be other -- better -- solutions, but it depends on the situation you are in (that I suspect is not shown by the example in the question)
这篇关于调用不同对象的闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!