項目中經常看到有人喜歡用Long.valueOf()去將String轉成long,我都忍不住去改Convert.asLong()。
原因是如果字符串不管是null還是空串,Long.valueOf()都會拋出異常,導致一些不必要的線上故障( java.lang.NumberFormatException : For input string: “”)。而Convert.asLong()能將null或空串直接轉成0,也可以指定默認值。
總結
我覺得相對來說,用Convert.asLong()能規避風險,減少調用Long.valueOf()之前的一系列爲空判斷。同理,其他類型轉換也是如此。
Long.valueOf()轉字符串其實也是調用parseLong()去實現的
下面是parseLong()部分源碼
public static long parseLong(String s, int radix)throws NumberFormatException
{
if (s == null) {
//如果字符串爲null,拋異常
throw new NumberFormatException("null");
}
int i = 0, len = s.length();
if (len > 0) {
//轉換
} else {
//空串拋異常
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
Convert.asLong()源碼
try {
return (new ConvertManager.ChainImpl(this, this.getTargetType(targetType))).convert(value);
} catch (ConvertFailedException var5) {
//有傳默認值返回默認值,沒有就0
if (var5.isDefaultValueSet()) {
return defaultValue == NO_DEFAULT_VALUE ? var5.getDefaultValue() : defaultValue;
} else {
throw var5;
}
}