是否有可能更改封闭的所有者? [英] Is it possible to change the owner of a closure?

查看:99
本文介绍了是否有可能更改封闭的所有者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在A类上有一个静态闭包,它将调用委托给B类。但是,当对A上的静态闭包使用A实例发出call()时,我似乎无法访问实例属性答:不要太惊讶,因为我正在使用静态闭包。解决此问题的一种方法是将实例化的A设置为闭包委托。然而,我需要类B是静态闭包的委托。



有无论如何,我可以改变静态闭包的所有者,所以它指向实例化的A类而不是静态?并保持B作为代表?或者这是不可能的?

解决方案

您错了......您可以更改关闭,但它是多么明智,我不知道(因为setter是私人的,这一定是有原因的)。无论如何,这里是一个例子:

  //定义一个Person,用一个闭包返回一个属性
class Person {
字符串名称
int age
Closure named = { - > 返回$ name}
}

//定义具有类似属性的另一个类
class家具{
字符串名称
int age
}

//创建我们的两个对象
def tim = new Person(name:'tim',age:26)
def chair = new Furniture(name:'chair ',年龄:3)

//打印返回的时间'
println tim.named()

//从tim添加闭包到椅子
chair.metaClass.named = tim.named
//打印'返回时间'
println chair.named()

//将所有者更改为椅子实例
tim.named。@ owner = chair
//打印'返回的椅子'
println chair.named()
//打印'返回的椅子'
println tim .named()

正如您所看到的,我们可以将所有者从Person类更改为Furniture class。



实际上,您可能想要设置闭包的代理而不是所有者,但是没有示例o f你试图达到的目标,不可能说这是否是你想要的

I have a static closure on Class A which delegates calls to Class B. However, when issuing a call() to the static closure on A with on a A instance i don't seem to have access to the instance properties on A. Not too suprising, as im working with a static closure. One way to solve this is ofc to set the instantiated A as the closures delegate. However, i need class B to be the delegate of the static closure.

Is there anyway i can change the owner of the static closure, so it points to the instantiated A class instead of the static? and keep B as the delegate? or is this impossible?

解决方案

You're wrong... you can change the owner of a Closure, but how advisable it is, I don't know (as the setter is private, there must be a reason for this). Anyway, here is an example:

// Define a Person, with a closure to return a property
class Person {
  String name
  int age
  Closure named = { -> "returned $name" }
}

// Define another Class with a similar property
class Furniture {
  String name
  int age
}

// Create our two objects
def tim = new Person( name:'tim', age:26 )
def chair = new Furniture( name:'chair', age:3 )

// Prints 'returned tim'
println tim.named()

// Add the closure from tim to the chair
chair.metaClass.named = tim.named
// Prints 'returned tim'
println chair.named()

// Change the owner to the chair instance
tim.named.@owner = chair
// prints 'returned chair'
println chair.named()
// prints 'returned chair'
println tim.named()

As you can see, we can change the owner from the Person class to the Furniture class.

In practice however, you probably want to be looking at setting the delegate for the closure rather than the owner, however with no examples of what you are trying to achieve, it is impossible to say whether this is what you wanted

这篇关于是否有可能更改封闭的所有者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆