@Accessors注解出现报错如何解决

发布时间:2021-06-16 13:48:14 作者:Leah
来源:亿速云 阅读:358

@Accessors注解出现报错如何解决,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

如下所示:

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
}

关于@Accessors注解出现报错如何解决问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. MYSQL的floor出现报错如何解决
  2. python中出现MemoryError报错如何解决

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

@accessors

上一篇:一个Servlet是怎么处理多个请求的

下一篇:怎么使用Python制作NFT区块链作品

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》