LoginSignup
2
0

More than 3 years have passed since last update.

【java編】シリアライズの話

Last updated at Posted at 2019-09-11

serialVersionUIDとは

 ランタイムシリアライゼーションはすべてのシリアライズクラスにバージョン番号を付与します。
 それはserialVersionUIDです。

 これは、シリアライズ化されたクラスをデシリアライズするとき、整合性チェックなどの認証を行います。
 もし、デシリアライズ後のクラスとクラスローダー中のクラスのserialVersionUIDが違うようになったら、
 デシリアライズ処理はInvalidClassException例外が発生します。

 シリアライズ可能なクラスは、自分自身のserialVersionUIDを定義することができます。
 ただし、 serialVersionUIDフィールドはstatic、long、finalではなければいけない。
 例:

private static final long serialVersionUID = 42L;

 もし、シリアライズ可能なクラスは、明示的にserialVersionUIDフィールドを定義しなければ、ランタイムシリアライゼーションより
 そのクラスのフィールド、メソッドなど、クラスの構造に基づいて計算してserialVersionUIDの値を自動生成します。

 それでも、すべてのシリアライズ可能なクラスはserialVersionUIDを明示的に宣言することを強くお勧めします。
 なぜというと、serialVersionUIDの計算方法はクラスの構造(計算時間もかかりそう)とJavaコンパイラに依存するため、
 デシリアライズ時を行うとき、想定外のInvalidClassExceptions例外が発生するかもしれません。

 だからこそ、違うJavaコンパイラーの環境でも、同じserialVersionUIDを保証するため、クラスはserialVersionUIDを明示的に
 宣言すべきです。
 
 また、できるだけ明示的なserialVersionUID宣言にprivate修飾子を使用することを強くお勧めします。

The serialization runtime associates with each serializable class a version number,
called a serialVersionUID,
which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class,
then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static,
final,
and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID,
then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class,
as described in the Java(TM) Object Serialization Specification. However,
it is strongly recommended that all serializable classes explicitly declare serialVersionUID values,
since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations,
and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore,
to guarantee a consistent serialVersionUID value across different java compiler implementations,
a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible.

※引用資料
What is a serialVersionUID and why should I use it?

※より一層理解したい方
難解なSerializableという仕様について俺が知っていること、というか俺の理解

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0