Closure in groovy cannot use private field when called from extending class

僤鯓⒐⒋嵵緔 提交于 2019-12-23 20:37:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!