In Groovy there is an @
operator which enables direct field access. However it looks like it won't work for fields declared in super class. Consider two Java (not Groovy) classes:
class Entity {
private Long id;
Long getId() {
return id;
}
}
class User extends Entity {
}
Then invoking direct access in Groovy
User user = new User();
user.@id = 1L
ends up with exception: groovy.lang.MissingFieldException: No such field: id for class User
When I try to use standard access user.id = 1L
I get groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: id for class User
Is there any option to access field declared in super class?
You would probably need to declare the property as protected instead:
class Entity {
protected Long id;
Long getId() {
return id * 2;
}
}
class User extends Entity {
}
User user = new User();
user.@id = 1L
assert user.@id == 1L
assert user.id == 2L
This is a modified example for the direct access field operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With