Private method in groovy is not private

后端 未结 5 2085
慢半拍i
慢半拍i 2020-12-18 19:12
class A {
    private def sayHello() {
       println \"Anish\"
    } 
 }

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

output : Anish

5条回答
  •  不知归路
    2020-12-18 19:27

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

提交回复
热议问题