我有查询我正在进行java中的序列化请告诉我如果我打开两个JVM实例,让我说我在两个不同的位置打开两个不同的eclipse工作空间我在一个工作空间中创建了程序来序列化具有.ser扩展名的文件中的对象,并通过另一个工作区创建程序,通过读取该.ser文件来反序列化该对象。
现在请告知该对象是否会在JVM的不同实例中反序列化?问题围绕这样一个事实:在JVM的同一个实例中对象序列化和反序列化是强制性的.. !!
答案 0 :(得分:1)
序列化是一个过程,通过它我们可以将对象的状态存储到任何存储介质中。我们可以将对象的状态存储到文件中,存储到数据库表等中。反序列化是序列化的相反过程,我们从存储介质中检索对象。
Eg1:假设你有一个Java bean对象,它的变量有一些值。现在,您希望将此对象存储到文件或数据库表中。这可以使用序列化来实现。现在,您可以在需要时随时从文件或数据库中再次检索此对象。这可以通过反序列化来实现。
**Serialization Example:**
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("employee.ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
**Deserializing an Object:**
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:
Employee e = null;
try
{
FileInputStream fileIn =
new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println(.Employee class not found.);
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
答案 1 :(得分:1)
Java serialization format is standardized。任何JVM都可以写入和读取它。
字节流可能略有不同(例如,序列化程序可能会以不同的顺序写入一些对象;如果一个类中有两个int
字段,那么它们的写入顺序无关紧要)
但是,除非您更改了存储在字节流中的类的Java代码,否则反序列化的结果将始终相同。