24

The following code sets a private method. So how private really is private?

public class Person {
 private String name
}

def u = new Person(name:"Ron")
println u.name
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • see http://stackoverflow.com/questions/3819794/how-to-define-private-getter-method-in-groovy-bean – tim_yates Oct 23 '10 at 21:03
  • 3
    @James - try it, it compiles without errors. – ripper234 Oct 24 '10 at 07:49
  • 2
    Groovy generates gettes/setters for private fields and if you try hit the private field like u.name Groovy invokes u.getName(){this.name} generated or declared method for it. So this behavior looks fine for me. Anyway Groovy has a lot of the issues with privacy ;) – dnim Sep 26 '13 at 07:18

2 Answers2

26

By design Groovy should respect the private modifier, however the current implementation takes no account of it.

There are further details in groovy call private method in Java super class

Rstew
  • 585
  • 2
  • 9
  • 21
mfloryan
  • 7,667
  • 4
  • 31
  • 44
0

I think we can access this because groovy adds getters and setters for all the variables. These methods are public, and hence private variables can be accessed outside the scope, that you would expect them be.

As in case of private methods, well you can get around anywhere with the concept of MetaClass.