Private method in groovy is not private

2019-01-26 05:23发布

class A {
    private def sayHello() {
       println "Anish"
    } 
 }

 def a_obj = new A()
 a_obj.sayHello()

output : Anish

Is there any way to protect sayHello() in groovy or am I missing something?

5条回答
forever°为你锁心
2楼-- · 2019-01-26 05:25

You can use closures to achieve a similar effect, basically the same way you would do information hiding with Javascript.

package test

class FunctionTests {

    def privilagedObj = {

        def privVar = 'foo'

        def privateFunc = { x -> println "${privVar} ${x}"}

        return {x -> privateFunc(x) } 
    }

    public static void main(String[] args) {

        def test = new FunctionTests().privilagedObj()

        test('bar')

    }
}
查看更多
Juvenile、少年°
3楼-- · 2019-01-26 05:27

There is defect on that in Groovy issue tracking system and that defect is still open.

查看更多
不美不萌又怎样
4楼-- · 2019-01-26 05:29

Searching for [groovy] private reveals:

groovy call private method in Java super class

What does 'private' mean in Groovy?

How to define private getter method in Groovy Bean?

It's not clear if it is a bug or by design, but it is going to get looked at again in Groovy 2.0

查看更多
5楼-- · 2019-01-26 05:31

As other posts have mentioned, this may be a bug in Groovy. I've been sticking to a simple convention of prefixing private member names with a leading underscore (similar to Python) to denote that it's private which helps me understand from a client side perspective what I should be calling.

查看更多
Anthone
6楼-- · 2019-01-26 05:43

I think its a bug in groovy that is fixed in groovy++.

http://jira.codehaus.org/browse/GROOVY-1875

查看更多
登录 后发表回答