Groovy中的“属性”是什么? [英] What are 'properties' in Groovy?
问题描述
当一个Groovy类定义声明一个没有访问修饰符的字段时,公共setter / getter方法对和一个私有实例根据 JavaBeans规范生成的变量字段也被称为属性 >。
class A {
字符串属性
/ *
private String属性
public void setProperty(String property){...}
public String getProperty(){...}
* /
}
如果我们声明一个公共实例变量字段,我们只需要一个公共字段,而不需要setter / getter方法对。
class A {
public String field
/ *
public String field
$ b 从Groovy客户端的pov, Groovy属性和运行时的公共字段
def a = new A()
println a.field
println a.property
虽然 a.field
直接访问实例变量,并且 a.property
实际调用 a.getProperty()
(或 a.setProperty(...)
wh分配一个值)。但是,由于该属性符合JavaBeans规范,因此该类可以无缝地用于基于Java的环境中。
我没有看到制作私有属性 。 private
限制方法或实例/类变量对托管类类型的使用。但也许你是指制作私人字段实例变量。
Properties in groovy seem like class fields in java without an access modifier. Is that true? Or they have a special meaning. It seems like there is no way to make the properties private?
解决方案 When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.
class A {
String property
/*
private String property
public void setProperty(String property) { ... }
public String getProperty() { ... }
*/
}
If we declare a public instance variable field we just get a public field, without a setter/getter method pair.
class A {
public String field
/*
public String field
*/
}
From a Groovy client's pov, there is no difference between accessing a Groovy property and a public field at runtime
def a = new A()
println a.field
println a.property
although a.field
accesses the instance variable directly and a.property
actually calls a.getProperty()
(or a.setProperty(...)
when assigning a value). But as the property complies to the JavaBeans spec, the class can seamlessly be used in Java-based environments.
I do not see much sense in making a "private property". private
restricts the use of a method or instance/class variable to the hosting class type. But maybe you were referring to making a private field instance variable.
这篇关于Groovy中的“属性”是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!