@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;
/**
* 數(shù)量
*/
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;
/**
* 數(shù)量
*/
private BigDecimal quantity;
public RefundOrderItem() {
super();
}
public RefundOrderItem(String itemTitle, BigDecimal quantity) {
this.itemTitle = itemTitle;
this.quantity = quantity;
}
}
}
lombok的@Accessors注解使用要注意
Accessors翻譯是存取器。通過該注解可以控制getter和setter方法的形式。
特別注意如果不是常規(guī)的get|set,如使用此類配置(chain = true或者chain = true)。在用一些擴展工具會有問題,比如 BeanUtils.populate 將map轉(zhuǎn)換為bean的時候無法使用。具體問題可以查看轉(zhuǎn)換源碼分析
@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
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java如何實現(xiàn)postman中用x-www-form-urlencoded參數(shù)的請求
在Java開發(fā)中,模擬Postman發(fā)送x-www-form-urlencoded類型的請求是一個常見需求,本文主要介紹了如何在Java中實現(xiàn)這一功能,首先,需要通過導入http-client包來創(chuàng)建HTTP客戶端,接著,利用該客戶端發(fā)送Post請求2024-09-09
Java中ExecutorService和ThreadPoolExecutor運行原理
本文主要介紹了Java中ExecutorService和ThreadPoolExecutor運行原理,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
IKAnalyzer使用不同版本中文分詞的切詞方式實現(xiàn)相同功能效果
今天小編就為大家分享一篇關(guān)于IKAnalyzer使用不同版本中文分詞的切詞方式實現(xiàn)相同功能效果,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12
Java hashCode原理以及與equals()區(qū)別聯(lián)系詳解
在 Java 應用程序執(zhí)行期間,在同一對象上多次調(diào)用 hashCode 方法時,必須一致地返回相同的整數(shù),前提是對象上 equals 比較中所用的信息沒有被修改。從某一應用程序的一次執(zhí)行到同一應用程序的另一次執(zhí)行,該整數(shù)無需保持一致2022-11-11

