为什么在使用 Kryo 时会出现 NullPointerException?

发布于 2024-11-14 22:09:32 字数 688 浏览 2 评论 0原文

这是我正在使用的完整代码。

Kryo kryo = new Kryo();
kryo.register(PlayerPOJO.class);
ByteBuffer buffer = ByteBuffer.allocateDirect(256);

PlayerPOJO pojo = new PlayerPOJO(1.0f, 1.0f);

kryo.writeObject(buffer, pojo);

PlayerPOJO player = kryo.readObject(buffer, PlayerPOJO.class);

System.out.println(player.getX() + ":" + player.getY());

PlayerPOJO 类只有两个浮点数以及它们的 get 方法。

我收到的错误是:

java.lang.NullPointerException 位于...

奇怪的是,这是来自 Kryo 站点的示例代码。我还尝试使用 readClassAndObjectwriteClassAndObject 出现相同的错误。

我尝试用 google 搜索该错误,但没有与该错误和 Kryo 相关的结果。关于 Kryo 的信息太少了,这是 SO 上关于 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(buffer, 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心作怪 2024-11-21 22:09:32

这不完全是示例代码...因为示例代码有一个“...”,表明您通常会做其他工作。

问题是,您永远不会“翻转”字节缓冲区,因此它不会读取您刚刚写入的数据。我强烈怀疑,如果您将代码更改为:

// 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...

...它很可能会起作用。调用flip有效意味着下一次读取将读取您刚刚写入的数据。顺便说一句,对 flip 的调用确实发生在某些示例代码中 - 仔细看看。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文