Search code examples
javagroovy

Groovy script and Java class without getter and setter with private fields, how does it access the fields?


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.


Solution

  • 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.