Java反序列化:final变量值未赋值

6 java serialization

我正在探索 Java 序列化和反序列化,但想知道反序列化是如何工作的。

这是我的序列化和反序列化代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Testing{
    public static void main(String[] args){
        Serial obj = new Serial();
        Serial ObjNew = null;
        try{
           FileOutputStream fob= new FileOutputStream("file.src"); 
           ObjectOutputStream oob= new ObjectOutputStream(fob);
           oob.writeObject(obj);
           oob.close();
        }catch(Exception fnf){
            fnf.printStackTrace(System.out);
        }
        try{
            FileInputStream fis = new FileInputStream("file.src");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ObjNew=(Serial)ois.readObject();
        }
        catch(IOException | ClassNotFoundException fnf){
            fnf.printStackTrace(System.out);
        }
        System.out.println("OLD: "+obj);
        System.out.println("NEW: "+ObjNew);

    }
}
Run Code Online (Sandbox Code Playgroud)

这里可序列化类代码:

import java.io.Serializable;
public class Serial implements Serializable {
    private final String ok="DONE";
    @Override
    public String toString(){
        return ok;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码一切正常。但是当我尝试用这段代码反序列化对象时。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Testing{
    public static void main(String[] args){
        Serial ObjNew = null;
        try{
            FileInputStream fis = new FileInputStream("file.src");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ObjNew=(Serial)ois.readObject();
        }
        catch(IOException | ClassNotFoundException fnf){
            fnf.printStackTrace(System.out);
        }
        System.out.println("NEW: "+ObjNew);

    }
}
Run Code Online (Sandbox Code Playgroud)

我只是更改了可序列化类中的值String ok="Do";只是为了测试反序列化输出。

但它只是打印而不是存储在文件中的Do值。DONE为什么只是打印Do为什么它不从文件中读取值? 有帮助吗?

And*_*res 1

一个final变量只能被赋值一次。

删除最后的修饰符,然后重试。