Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field access in Groovy for super class

Tags:

groovy

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?

like image 239
Jakub Kubrynski Avatar asked Mar 14 '16 15:03

Jakub Kubrynski


1 Answers

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.

like image 80
Fran García Avatar answered Sep 28 '22 17:09

Fran García