Groovy中的“属性”是什么?

编程入门 行业动态 更新时间:2024-10-19 01:17:47
本文介绍了Groovy中的“属性”是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 groovy中的属性看起来像java中没有访问修饰符的类字段。真的吗?或者他们有特殊的含义。似乎没有办法让这些属性变成私人的?

解决方案

当一个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中的“属性”是什么?

本文发布于:2023-11-02 14:06:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   Groovy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!