为什么simpleDateFormat.format(null)会报空指针异常
2018-11-21 13:00
197 查看
[code]SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.format(null);
在第二行会报空指针异常,为什么呢?
我们进入源码看一下就知道了。
第一步
public final String format(Date date)
{
return format(date, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
这里date为null,没问题,继续;
第二步
[code]public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) { pos.beginIndex = pos.endIndex = 0; return format(date, toAppendTo, pos.getFieldDelegate()); }
这里date为null也没问题,继续;
第三步
[code]private StringBuffer format(Date date, StringBuffer toAppendTo, FieldDelegate delegate) { calendar.setTime(date); ...... }
这里date为null也没问题,进入calendar.setTime看一下;
第四步
[code]public final void setTime(Date date) { setTimeInMillis(date.getTime()); }
这里date为null,就变成null.getTime(),必然会报空指针异常;
由于空指针异常是运行时异常,编译时不会被检查出来,所以在使用SimpleDateFormat的format(Date date)方法时,请做非空判断,或异常处理。
相关文章推荐
- java中设置日期格式的方式一般用SimpleDateFormat("YY-MM-dd")就可以了,但为什么有的 SimpleDateFormat("YY-MM-dd",locale.getDefau
- 为什么date.toString()不具备安全性而要使用SimpleDateFormat?
- 为什么static修饰SimpleDateFormat会有问题
- SimpleDateFormat NULL
- SimpleDateFormat 为什么不是线程安全的
- java日期格式大全 format SimpleDateFormat
- SimpleDateFormat 的使用注意点
- java25:SimpleDateFormat;DateFormat
- SimpleDateFormat使用详解
- SimpleDateFormat线程不安全及解决的方法
- SimpleDateFormat、Calendar、Date
- Java SimpleDateFormat中英文时间格式化转换详解
- 关于jdk1.7的SimpleDateFormat类线程不安全
- Java格式化日期类DateFormat和SimpleDateFormat的学习
- SimpleDateFormat的用法
- Java中SimpleDateFormat的使用方法
- 深入理解Java:SimpleDateFormat安全的时间格式化
- 一些共通的方法(今日の日付,排序,YY/MM/DD,SimpleDateFormat)
- 深入理解Java:SimpleDateFormat安全的时间格式化
- simpleDateFormat