Groovy @ symbol before fields

2019-03-14 09:14发布

What does @ means before a field name in Groovy? For some classes I am able to access private fields that are not directly accessible, let's take ComposedClosure for example:

public class Person {
  private String name
}

def u = new Person(name:"Ron")
println u.@name //Ron
println u.name //Ron

a = {2} >> {3}
println a.@first //first closure object
println a.first //runtime error

2条回答
叼着烟拽天下
2楼-- · 2019-03-14 10:08

It allows you to override groovy's use of property accessors. If you write:

println u.name

groovy will invoke the automatically generated getter Person.getName(). If you write:

println u.@name

it will go directly to the field like it would in Java. In the case of the closure, it seems to have a first field but not a corresponding getFirst accessor.

In the groovy manual, it's documented as the direct field access operator.

查看更多
唯我独甜
3楼-- · 2019-03-14 10:15

It means you're accessing a field directly, rather than going through a getter.

See the Groovy operator docs, although there isn't much more to say. Other than probably avoid it.

The reason it fails for a ComposedClosure is because there's no getter for first (or second).

查看更多
登录 后发表回答