Groovy 中的“属性"是什么? [英] What are 'properties' in Groovy?

查看:29
本文介绍了Groovy 中的“属性"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

groovy 中的属性看起来就像 java 中没有访问修饰符的类字段.真的吗?或者它们有特殊的含义.似乎没有办法将属性设为私有?

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?

推荐答案

当一个 Groovy 类定义声明一个没有访问修饰符的字段时,就会生成一个公共的 setter/getter 方法对和一个私有的实例变量字段,这也是已知的根据 JavaBeans 规范,作为属性".

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() { ... }
    */
}

如果我们声明一个公共实例变量字段,我们只会得到一个公共字段,没有 setter/getter 方法对.

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
    */
}

从 Groovy 客户端的观点来看,在运行时访问 Groovy 属性和访问公共字段没有区别

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

虽然 a.field 直接访问实例变量并且 a.property 实际上调用了 a.getProperty()(或 a.setProperty(...) 赋值时).但由于该属性符合 JavaBeans 规范,因此该类可以在基于 Java 的环境中无缝使用.

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.

我认为制作私有财产"没有多大意义.private 将方法或实例/类变量的使用限制为宿主类类型.但也许您指的是创建一个私有字段实例变量.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆