如何在 Java 中测试类是否正确实现了 Serializable(不仅仅是 Serializable 的实例) [英] how to test in Java that a class implements Serializable correctly (not just is an instance of Serializable)

查看:11
本文介绍了如何在 Java 中测试类是否正确实现了 Serializable(不仅仅是 Serializable 的实例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个可序列化的类(因此它是一个使用 RMI 的值对象).但我需要测试一下.有没有办法轻松做到这一点?

I am implementing a class to be Serializable (so it's a value object for use w/ RMI). But I need to test it. Is there a way to do this easily?

澄清:我正在实现这个类,所以在类定义中坚持 Serializable 是微不足道的.我需要手动序列化/反序列化它以查看它是否有效.

clarification: I'm implementing the class, so it's trivial to stick Serializable in the class definition. I need to manually serialize/deserialize it to see if it works.

我发现了这个 C# 问题,Java 有类似的答案吗?

I found this C# question, is there a similar answer for Java?

推荐答案

简单的方法是检查对象是 java.io.Serializablejava.io 的实例.可外部化,但这并不能真正证明该对象确实是可序列化的.

The easy way is to check that the object is an instance of java.io.Serializable or java.io.Externalizable, but that doesn't really prove that the object really is serializable.

唯一可以确定的方法是真实尝试.最简单的测试是这样的:

The only way to be sure is to try it for real. The simplest test is something like:

new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(myObject);

并检查它没有抛出异常.

and check it doesn't throw an exception.

Apache Commons Lang 提供了一个更简洁的版本:

Apache Commons Lang provides a rather more brief version:

SerializationUtils.serialize(myObject);

再次检查异常.

您还可以更严格,并检查它是否反序列化回与原始内容相同的内容:

You can be more rigourous still, and check that it deserializes back into something equal to the original:

Serializable original = ...
Serializable copy = SerializationUtils.clone(original);
assertEquals(original, copy);

等等.

这篇关于如何在 Java 中测试类是否正确实现了 Serializable(不仅仅是 Serializable 的实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆