Lombok使用@Data的大坑,空指针错误

之前生产环境报了一个神奇的错误,接口调用时,入参直接空指针!

模拟一下当时的错误:

入参实体类如下:

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import org.apache.commons.lang.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Ayton Echo
 * @date 2022年01月21日 10:31
 */
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Test {
	String oderName;

	String orderType;

	private String orderTypeWithLabel;

	private static final Map<String, String> orderTypeMap = new ConcurrentHashMap<>();

	static {
		orderTypeMap.put("a", "xx1");
		orderTypeMap.put("b", "xx2");
	}

	public String getOrderTypeWithLabel() {
		String label = orderTypeMap.get(this.orderType);
		if (StringUtils.isEmpty(label)) {
			return this.orderType;
		} else {
			return this.orderType + "-" + orderTypeMap.get(this.orderType);
		}
	}
}

执行一段:

public static void main(String[] args) {
	Test test = new Test();
	test.setOrderType(null);
	System.out.println(test);
}

报错:

Exception in thread "main" java.lang.NullPointerException

原因是:

@Data注解中有默认toString方法的重写,展示数据时,默认调用get方法的方式。

所以当你的get方法中有计算或者调用时,而你的属性值是null,就会报错。

上面例子中getOrderTypeWithLabel() 方法中的 this.orderType 是null,所以走get方法时,出错了。

解决办法有两个,自行选择即可:

1、修改getOrderTypeWithLabel() 方法的逻辑。

public String getOrderTypeWithLabel(){
	if(this.orderType != null){
		String label = orderTypeMap.get(this.orderType);
		if(StringUtils.isEmpty(label)){
			return this.orderType;
		}else{
			return this.orderType+"-"+orderTypeMap.get(this.orderType);
		}
	}else {
		return null;
	}
}

2、实体类添加 @ToString(doNotUseGetters = true) 注解

这个注解的意思是展示数据时,不会默认调用get方法了,而是直接取属性的值。(默认是false)

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Ayton Echo
 * @date 2022年01月21日 10:31
 */
@Data
@ToString(doNotUseGetters = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Test {
	String oderName;

	String orderType;

	private String orderTypeWithLabel;

	private static final Map<String, String> orderTypeMap = new ConcurrentHashMap<>();

	static {
		orderTypeMap.put("a", "xx1");
		orderTypeMap.put("b", "xx2");
	}

	public String getOrderTypeWithLabel() {
		String label = orderTypeMap.get(this.orderType);
		if (StringUtils.isEmpty(label)) {
			return this.orderType;
		} else {
			return this.orderType + "-" + orderTypeMap.get(this.orderType);
		}
	}
}

执行后:

Test(oderName=null, orderType=null, orderTypeWithLabel=null)

至此,问题解决,特此记录。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值