码迷,mamicode.com
首页 > 其他好文 > 详细

"Serializable" classes should have a version id

时间:2017-07-21 18:56:28      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:raspberry   ignore   exce   when   val   mod   err   new   explicit   

serialVersionUID field is required in all Serializable classes. If you do not provide one, one will be calculated for you by the compiler. The danger in not explicitly choosing the value is that when the class changes, the compiler will generate an entirely new id, and you will be suddenly unable to deserialize (read from file) objects that were serialized with the previous version of the class.

serialVersionUID‘s should be declared with all of these modifiers: static final long.

Noncompliant Code Example

public class Raspberry extends Fruit  // Noncompliant; no serialVersionUID.
        implements Serializable {
  private String variety;

  public Raspberry(Season ripe, String variety) { ...}
  public void setVariety(String variety) {...}
  public String getVarity() {...}
}

public class Raspberry extends Fruit
        implements Serializable {
  private final int serialVersionUID = 1; // Noncompliant; not static & int rather than long

Compliant Solution

public class Raspberry extends Fruit
        implements Serializable {
  private static final long serialVersionUID = 1;
  private String variety;

  public Raspberry(Season ripe, String variety) { ...}
  public void setVariety(String variety) {...}
  public String getVarity() {...}
}

Exceptions

Swing and AWT classes, abstract classes, Throwable and its subclasses (Exceptions and Errors), and classes marked with @SuppressWarnings("serial") are ignored.

"Serializable" classes should have a version id

标签:raspberry   ignore   exce   when   val   mod   err   new   explicit   

原文地址:http://www.cnblogs.com/winner-0715/p/7219083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!