问题
I have a class in groovy, where I have a private field, and a method. In the method, I call http service, and pass a closure there to handle the response. Something like this:
class WebUiRestRequestSender {
private String jSessionIdCookie
def login(String username, String password) {
//...
httpClient.post(
path: login,
body: parameters,
requestContentType : URLENC
) { resp, reader ->
jSessionIdCookie = getSessionCookie(resp)
}
}
}
Everything works fine when I create object of this class and call this method. However, when I inherit from this class, and try to call the method from inheriting class, I'm getting error:
groovy.lang.MissingPropertyException: No such property: jSessionIdCookie for class: ResellerWebUiRestRequestSender
Why is that? Why superclass method cannot see property defined in superclass in Groovy?
回答1:
Default access modifier in Groovy is public, which helps in creating POGOs seamlessly as Groovy adds the accessor methods automatically at class generation.
When the access modifier is changed to private, groovy does not create any accessor method for that property. In order to access that private property as a read-only property
getJSessionIdCookie() method has to be added to the base class.
getJSessionIdCookie() { jSessionIdCookie }
Now, when you access jSessionIdCookie in sub-class, getProperty metaclass implementation will invoke the above getter method instead.
来源:https://stackoverflow.com/questions/24071667/closure-in-groovy-cannot-use-private-field-when-called-from-extending-class