java中序列化对象并赋值
时间: 2024-02-22 15:57:12 浏览: 20
Java 中可以通过对象序列化的方式来将一个对象序列化为字节流,然后将字节流保存到文件或网络中。反过来,可以从文件或网络中读取字节流,然后将其反序列化为一个对象。在反序列化的过程中,对象的属性值会被赋值为序列化时的值。以下是一个简单的示例:
```java
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Employee e = new Employee();
e.name = "Tom";
e.address = "Shanghai";
e.number = 101;
try {
// 将对象序列化为字节流并写入文件
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser");
// 从文件中读取字节流并反序列化为对象
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee e2 = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized data: " + e2.name + " " + e2.address + " " + e2.number);
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
}
}
}
class Employee implements Serializable {
public String name;
public String address;
public transient int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
```
在上面的示例中,我们定义了一个 Employee 类,并实现了 Serializable 接口,这样我们就可以将 Employee 对象序列化为字节流。在 main 方法中,我们首先创建一个 Employee 对象,并设置其属性值。然后将该对象序列化为字节流,并写入到文件 employee.ser 中。接着,我们从文件中读取字节流,并将其反序列化为一个新的 Employee 对象。最后,输出新的 Employee 对象的属性值,即可看到对象已经被成功反序列化并赋值。