广告
返回顶部
首页 > 资讯 > 后端开发 > Python >@Accessors(chain = true)注解报错的解决方案
  • 581
分享到

@Accessors(chain = true)注解报错的解决方案

2024-04-02 19:04:59 581人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

如下所示: Cannot invoke setItemTitle(String) on the primitive type void 定义的实体类如下: @Data

如下所示:

Cannot invoke setItemTitle(String) on the primitive type void

定义的实体类如下:


  @Data
  public static class RefundOrderItem implements Serializable {
    
    @JSONProperty("item_title")
    private String itemTitle;
    
    private BigDecimal quantity;
    public RefundOrderItem() {
      super();
    }
    public RefundOrderItem(String itemTitle, BigDecimal quantity) {
      this.itemTitle = itemTitle;
      this.quantity = quantity;
    }
  }
}

这种写法不报错


request.getItems()
.add(new RefundOrderItem(productPO.getName(), quantity));

这种写法报错


request.getItems()
.add(new RefundOrderItem().setItemTitle(productPO.getName()).setQuantity(quantity)));

上述报错的解决方法如下:

在定义的实体类上加上注解:@Accessors(chain = true)

实体类代码如下:


@Data
  @Accessors(chain = true)
  public static class RefundOrderItem implements Serializable {
    
    @jsonProperty("item_title")
    private String itemTitle;
    
    private BigDecimal quantity;
    public RefundOrderItem() {
      super();
    }
    public RefundOrderItem(String itemTitle, BigDecimal quantity) {
      this.itemTitle = itemTitle;
      this.quantity = quantity;
    }
  }
}

lombok的@Accessors注解使用要注意

Accessors翻译是存取器。通过该注解可以控制getter和setter方法的形式。

特别注意如果不是常规的get|set,如使用此类配置(chain = true或者chain = true)。在用一些扩展工具会有问题,比如 BeanUtils.populate 将map转换为bean的时候无法使用。具体问题可以查看转换源码分析

@Accessors(fluent = true)#

使用fluent属性,getter和setter方法的方法名都是属性名,且setter方法返回当前对象


class Demo{
    private String id;
    private Demo id(String id){...}  //set
    private String id(){} //get
}

@Accessors(chain = true)#

使用chain属性,setter方法返回当前对象


class Demo{
    private String id;
    private Demo setId(String id){...}  //set
    private String id(){} //get
}

@Accessors(prefix = "f")#

使用prefix属性,getter和setter方法会忽视属性名的指定前缀(遵守驼峰命名)


class Demo{
    private String fid;
    private void id(String id){...}  //set
    private String id(){} //get
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: @Accessors(chain = true)注解报错的解决方案

本文链接: https://www.lsjlt.com/news/128307.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作