ByteBuffer在最后一个值为null时翻转

时间:2017-07-26 16:57:29

标签: java bytebuffer flip

我有一个应该返回ByteBuffer的方法。该方法的内容如下:

if (true) {
    //code that puts some data into ByteBuffer bb
    return bb
}
else {
    //should not be writing any data to bb 
    //intention: leave bb as is
    return null;
}

在调用此方法并将必要的数据放入ByteBuffer后,我首先调用bb.flip()将其转换为字节数组。但是,如果通过if-else循环的最后一次迭代恰好为假,则输入的最后一个数据为null,我得到java.lang.NullPointerException错误。

Allocating zero capacity ByteBuffer

根据上面的页面,我应该返回一个零长度的ByteBuffer,但我不确定如何返回类似的东西。

关于如何返回空字节缓冲区的任何想法?

2 个答案:

答案 0 :(得分:0)

由于你要在任何一种情况下使用ByteBuffer,该方法应该无条件地返回它 - 返回null只会导致你观察到的错误。

为了使这段代码更清晰,我只是让方法返回类型SELECT count(CASE WHEN business_day < date(getdate()) THEN 1 END) as passed ,count(business_day) as total_business_days FROM (SELECT distinct date(o.appointment_full_time) as business_day FROM orders o WHERE date_trunc('month', o.appointment_full_time) = date_trunc('month', getdate()) --this month AND extract(dow from o.appointment_full_time) not in (0,6) --exclude weekends AND date(o.appointment_full_time) not in ('2017-1-1', '2017-1-2', '2017-1-16', '2017-5-29', '2017-7-4', '2017-9-4', '2017-11-23', '2017-11-24', '2017-12-25', '2017-12-24', '2017-12-31') --manually enter the holidays in once per year ) a 。该方法可以通过调用方法将字节添加到ByteBuffer(或不是)中 - 这里的返回值实际上是多余的。

答案 1 :(得分:0)

在else块中使用以下语句来避免NPE(空指针异常)

返回ByteBuffer.allocate(0);