当从扩展类调用时,groovy中的Closure不能使用私有字段 [英] Closure in groovy cannot use private field when called from extending class

查看:215
本文介绍了当从扩展类调用时,groovy中的Closure不能使用私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在groovy有一个类,我有一个私有字段和一个方法。在该方法中,我调用http服务,并在那里传递一个闭包来处理响应。类似的东西:

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)
        }
    }
}


$ b b

当我创建这个类的对象并调用这个方法时,一切正常。但是,当我从这个类继承,并尝试从继承类调用该方法,我收到错误:

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

为什么?为什么超类方法看不到在Groovy中的超类中定义的属性?

Why is that? Why superclass method cannot see property defined in superclass in Groovy?

推荐答案

Groovy中的默认访问修饰符是 public ,当Groovy在类生成时自动添加访问器方法时,可以无缝创建POGO。

Default access modifier in Groovy is public, which helps in creating POGOs seamlessly as Groovy adds the accessor methods automatically at class generation.

当访问修饰符更改为 private ,groovy不会为该属性创建任何访问器方法。为了访问作为只读属性的私有属性,
getJSessionIdCookie()方法必须添加到基类中。

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 }

现在,当您在子类中访问 jSessionIdCookie 时, getProperty 元类实现将调用上述getter方法。

Now, when you access jSessionIdCookie in sub-class, getProperty metaclass implementation will invoke the above getter method instead.

这篇关于当从扩展类调用时,groovy中的Closure不能使用私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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