如何使用相同SerialUid在Java序列化中实现版本控制?

时间:2019-05-29 04:37:25

标签: java serialization version-control

我有以下实现序列化的类。

<table id="detail_table" class="detail">  
    <thead>  

    <tr>  
    <th>ID</th>  
    <th colspan="2">Name</th>  
    </tr>  
    </thead>  
    <tbody>  
    <tr class="parent" id="row101" title="Click to expand/collapse" 
    style="cursor: pointer;">  
    <td>101</td>  
    <td colspan="2">File Management Tool</td>  
    </tr> 

    <tr class="child-row101" style="display: none;">  
    <td> </td>  
    <td>New File Tool</td>
    </tr>  

    <tr class="child-row101" style="display: none;">  
    <td> </td>  
    <td>Transfer Report</td>  
    </tr>

我尝试使用以下代码将User类对象保存在文本文件中。基本上,我尝试先编写对象然后再读取它。

class User implements Serializable{

    public User(String username, String password) {
        this.username=username;
        this.password=password;
    }

    private static final long serialVersionUID = 1L;
    String username;
    String password;

}

它给出输出public class SerializableExample { public static void main(String[] args) { User user = new User("userB","passwordB"); String filename = "E:\\Proj-docs\\userFile.txt"; FileOutputStream file; try { file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(user); out.close(); file.close(); } catch (IOException e) { e.printStackTrace(); } User user2=null; try { FileInputStream file2 = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file2); user2= (User) in.readObject(); Optional checkNull = Optional.ofNullable(user2); if(checkNull.isPresent()) { System.out.println(user2.username + " "+user2.password); }else { System.out.println("Null Object"); } }catch(IOException | ClassNotFoundException e) { e.printStackTrace(); } } } 现在,假设我想更改用户对象并将其存储在同一文本文件中

userB passwordB

现在,如果我阅读了User对象,它会给出public class SerializableExample { public static void main(String[] args) { User user = new User("userD","passwordD"); String filename = "E:\\Proj-docs\\userFile.txt"; FileOutputStream file; try { file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(user); out.close(); file.close(); : : :

我的问题是,即使在更新用户之后,我是否仍可以使用serialVersionUID检索用户的旧版本(值为userD passwordD的用户)?我想看看在更新对象或向类中添加新属性而不更改串行uid时如何在Java序列化中使用版本控制。

谢谢您的输入。

0 个答案:

没有答案