加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy中的超级类字段访问

发布时间:2020-12-14 16:26:20 所属栏目:大数据 来源:网络整理
导读:在Groovy中有一个@运算符,可以直接访问字段.但是看起来它对超类中声明的字段不起作用.考虑两个 Java(不是Groovy)类: class Entity { private Long id; Long getId() { return id; }}class User extends Entity {} 然后在Groovy中调用直接访问 User user = n
在Groovy中有一个@运算符,可以直接访问字段.但是看起来它对超类中声明的字段不起作用.考虑两个 Java(不是Groovy)类:

class Entity {
  private Long id;

  Long getId() {
    return id;
  }
}

class User extends Entity {
}

然后在Groovy中调用直接访问

User user = new User();
user.@id = 1L

以异常结束:groovy.lang.MissingFieldException:没有这样的字段:类User的id

当我尝试使用标准访问user.id = 1L时,我得到了groovy.lang.ReadOnlyPropertyException:无法设置readonly属性:id for class User

是否有任何选项可以访问超类中声明的字段?

解决方法

您可能需要将该属性声明为受保护的:

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

这是直接访问字段运算符的修改示例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读