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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

贝小贝貝   2021-06-16 我要评论
想了解@Accessors(chain = true)注解报错的解决方案的相关内容吗,贝小贝貝在本文为您仔细讲解@Accessors(chain = true)注解的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:@Accessors,chain=true,注解报错,下面大家一起来学习吧。

如下所示:

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
}

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们