如何在Groovy中从trait实现中获取属性?
我有一个特质,叫做如何在Groovy中从trait实现中获取属性?,groovy,Groovy,我有一个特质,叫做MyTrait package properties trait MyTrait { abstract String property String getThatProperty() { "$property is that property" } } 然后我有一个实现这个特性的类 package properties class PropertiesTesting implements MyTrait { String
MyTrait
package properties
trait MyTrait {
abstract String property
String getThatProperty() {
"$property is that property"
}
}
然后我有一个实现这个特性的类
package properties
class PropertiesTesting implements MyTrait {
String property = 'Hello'
}
问题是,当我去调用
PropertiesTesting#gethatproperty()
时,它返回“null是该属性”
。如何修复该问题,使其返回“x是该属性吗”
,并且x
根据实现的不同而变化?我不想为实现trait的每个类重写代码。答案是简单地使用object.properties
package properties
class PropertiesTesting implements MyTrait {
String property = 'Hello'
}
要获取
PropertiesTesting
的属性property
,我可以使用instance.properties['property']
我不同意将状态封装在trait中是一个好的选择。尽管这看起来可能是可行的,但它也带来了与使用状态扩展类相同的问题
问题的解决方案甚至更简单——让您的trait定义抽象字符串getProperty()
方法。大概是这样的:
trait MyTrait {
abstract String getProperty()
String getThatProperty() {
"$property is that property"
}
}
class PropertiesTesting implements MyTrait {
String property = 'Hello'
}
def properties = new PropertiesTesting()
assert properties.getThatProperty() == 'Hello is that property'
在
PropertiesTesting
中添加一个字段property
会添加一个合适的getProperty()
方法,当您调用特性is的gethatproperty()
方法时,将使用getProperty()
中的。它更简单、更直接。它接受trait的属性(为null)而不是类的属性。
如果要打印句子,请注释掉trait的String属性并添加println命令
package properties
trait MyTrait {
//abstract String property
String getThatProperty() {
println "$property is that property"
}
}
class PropertiesTesting implements MyTrait {
String property = 'Hello'
}
def instance = new PropertiesTesting()
instance.getThatProperty()
应该是这个。属性['property']