[英]What is the purpose of automatically generating getters and setters when the backing field is public
From the properties section of the Groovy documentation : 从Groovy 文档的properties部分:
class Person {
String name
int age
}
You can define a property with:
您可以使用以下方法定义属性:
an absent access modifier (no public, protected or private)
缺少访问修饰符(无公共,受保护或私有)
...
...
Groovy will then generate the getters/setters appropriately
Groovy然后将适当地生成吸气剂/吸气剂
So with the above code snippet, I can do this: 因此,使用上面的代码片段,我可以做到这一点:
Person sveta = new Person("Sveta",22)
println(sveta.getname())
println(sveta.name)
Question: Why would you want to do this? 问题:您为什么要这样做?
What is the purpose of declaring a variable with no access modifier and allowing the getter/setters
be generated for you automatically when I can still access the field directly, and circumvent the setter? 声明没有访问修饰符的变量并允许我在仍然可以直接访问该字段并规避setter的情况下自动为您生成
getter/setters
的目的是什么?
I'm not asking what the purpose of a setter is or why I would want to use one, what I'm asking is, Groovy generates the getter/setter
for you under certain circumstances, but in production when would you want to do this? 我不是在问设置器的目的是什么,或者为什么要使用它,我要问的是,Groovy在某些情况下会为您生成
getter/setter
,但是在生产中您什么时候想要这样做?
For me it is just a convenience for when you need to have a Java style bean object (for example to pass to a library or framework) with getters and setters and not to have to type and maintain all the getter and setter code / boilerplate. 对我来说,这是一种方便,当您需要具有带有getter和setter的Java样式bean对象(例如,传递给库或框架),而不必键入和维护所有getter和setter代码/样板文件时。 Also, when you access the field directly as in your example, it is still calling the getter and setter so the getters and setters in Groovy can provide custom functions or side effects (potentially not desirable) that are called even when direct field access is used.
同样,当您像示例中一样直接访问字段时,它仍在调用getter和setter,因此即使在使用直接字段访问时,Groovy中的getter和setter也可以提供被调用的自定义函数或副作用(可能不理想) 。 Like this:
像这样:
import groovy.transform.ToString
@ToString
class Person {
String name
int age
String getName() {
if(name == 'fred') {
return 'fred bloggs'
}
else {
return name
}
}
}
def p = new Person()
p.name = 'fred'
assert p.name == 'fred bloggs'
assert p.getName() == 'fred bloggs'
println p.toString()
p.name = 'sally'
assert p.name == 'sally'
assert p.getName() == 'sally'
println p.toString()
Results in this output: 结果如下:
Person(fred bloggs, 0)
Person(sally, 0)
But you are right, I think the why of this needs to be more clearly explained in the Groovy documentation. 但是您是对的,我认为需要在Groovy文档中更清楚地解释其原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.