1

I have java class like

class Test {

   private String field1;
}

no other methods or getter and setter.

in a groovy script I have:

def test = new Test()

test.field1 = "foobar"

and this works even if the field is private and no getter/setter are defined. How does it works?

The project is a java project and the groovy script is executed via GroovyShell so the Test class is compiled by java (no methods added by groovy).

Thanks for the help.

res1
  • 3,482
  • 5
  • 29
  • 50
  • 1
    Groovy accesses the field directly (internally by using reflection). That's actually one of the pitfalls of Groovy that made me switch away from it: it's way too easy to accidentally access an objects internals even when you didn't mean to. – Joachim Sauer Jul 11 '23 at 13:26
  • 1
    I wonder how this holds up when you use a JVM with the module system enabled. Those tend to not like reflective access to privates. – Jorn Jul 11 '23 at 15:33
  • @Jorn Interesting point, it would be nice to know how it works in this case. – res1 Jul 11 '23 at 16:00

1 Answers1

1

Groovy uses Reflection API to access fields, so there is not real "privacy" here. Check this question, people discuss it more in details. Also check this article.

Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22