Calling closure on different object?

馋奶兔 提交于 2019-12-01 11:05:15

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

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.

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)

I believe closure "includes" the enclosing object to act upon. It is not possible override "this" inside a closure at runtime.

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