Why am I getting this NullPointerException when using Kryo?
Here's the entire code I'm using.
Kryo kryo = new Kryo();
kryo.register(PlayerPOJO.class);
ByteBuffer buffer = ByteBuffer.allocateDirect(256);
PlayerPOJO pojo = new PlayerPOJO(1.0f, 1.0f);
kryo.writeObject(b开发者_如何学运维uffer, pojo);
PlayerPOJO player = kryo.readObject(buffer, PlayerPOJO.class);
System.out.println(player.getX() + ":" + player.getY());
The PlayerPOJO class only has two floats and the get methods for those.
The error I'm getting is:
java.lang.NullPointerException at ...
The strange thing is that this is the example code from the Kryo site. I have also tried to used readClassAndObject
and writeClassAndObject
with the same error.
I tried to google the error but there are no results relating to this error and Kryo. There is so little information about Kryo that this is the 4th question about Kryo on SO.
It's not exactly the example code... because the example code has a "..." suggesting you'd normally do other work.
The trouble is, you're never "flipping" your byte buffer, so it's not reading the data you've just written. I strongly suspect that if you change your code to:
// Code as before...
kryo.writeObject(buffer, pojo);
// This call is all that's new
buffer.flip();
PlayerPOJO player = kryo.readObject(buffer, PlayerPOJO.class);
// Code as before...
... it may well just work. The call to flip effectively means that the next read will read the data you've just written. The call to flip
does occur in some sample code, by the way - have a close look.
精彩评论