Java serialVersionUID作用

來源:互聯網
上載者:User

標籤:char   class   zab   NPU   port   http   fileinput   sse   com   

今天在學習Java的檔案輸入輸出時,學習了進階流ObjectInputStream,它使用了是序列化的寫入和寫出,在寫出的時候遇到了一個錯誤:java.io.InvalidClassException:local class incompatible: stream classdesc serialVersionUID = …, local class serialVersionUID = …

在網上找了一些solution,解決辦法如下:在實現serializable介面的類中,定義一個serialVersionUID變數,類型為public static final long,以我的為例:

public final static long serialVersionUID = -8497580858753153590l;

具體的作用我是參考的這一篇文章,May it helpful!   http://swiftlet.net/archives/1268

下面提一下代碼:

 1 import java.io.Serializable; 2 import java.util.List; 3  4 public class Person implements Serializable{ 5     private String name; 6     private int age; 7     private char sex; 8     private List<String> list; 9     public final static long serialVersionUID = -8497580858753153590l;10     11     Person(String name,int age,char sex,List<String> list){12         this.name = name;13         this.age = age;14         this.sex = sex;15         this.list = list;16     }17     public String toString(){18         return name+" "+age+" "+sex+" "+list;19     }20 21 }

上面是構造的一個輔助類,下面是流的執行個體類。

 1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 public class OIS { 6  7     public static void main(String[] args) throws IOException, ClassNotFoundException { 8         // TODO Auto-generated method stub 9         FileInputStream  fis = new FileInputStream("person.obj");10         ObjectInputStream ois = new ObjectInputStream(fis);11         Person per = (Person)ois.readObject();12         13         System.out.println(per);14         ois.close();15 16     }17 18 }

 

 

Java serialVersionUID作用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.