Groovy类如何定义只读 属性(Property) ?

首先明确Groovy定义的两个概念:

  • Property 属性: 所谓类的 property 是从外看到的对象状态,是用get/set method访问一个对象状态的方法。例如: obj1.name,这里name就是对象obj1的一个属性(Property),其实是在访问 obj1.getName() 方法。一般这个访问不是在 obj1 类的内部访问,而是在外部访问的。

  • Field 字段:所谓类的 field,是类的成员变量,它的值不通过 get/set method 来访问。例如:this.name,这里就是在访问类的 field ‘name’。在类的外部,Groovy 默认用 property 方式来访问对象的状态,只有在内部才能用 this 访问到 field。如果一定要从外部访问一个类的field,可以用 obj1.@name这种格式。

Groovy 文档说:
定义一个 Property 的条件是 “没有访问修饰符,一个static、final 或者 synchronized,可选的类型,必有的名字”

You can define a property with:

  • an absent access modifier (no public, protected or private)
  • one or more optional modifiers (static, final, synchronized)
  • an optional type
  • a mandatory name

并且,如果声明为 final 就不会生成 set 方法,即 property 变为只读的了。

If a property is declared final, no setter is generated.

也就是说如果你在 field 前面用了 final 就不会生成该属性的 set 方法。

实际使用只读property时,遇到一个局限就是用 final 修饰符修饰 property 后,在内部也无法重新赋值,因为 property 对应的 field 是 final 的。也即这里的只读,是真的只读,任何地方都是只能读。

如果要达到内部可改只读属性,那么可以通过显式定义 field 和 get 方法来实现。如下:

class Foo {
  private String name = "yang"
  String getName(){
  	name
  }
}

Foo foo = new Foo()
assert foo.name == "yang"
// error
foo.name = "bo"

这样就可以了。

参考

Groovy Document: fields and properties

发布了63 篇原创文章 · 获赞 25 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/yangbo_hr/article/details/105070684