正如问题所说,JVM 对实现 Marker 接口的类给予了额外的处理。例如,我使用 Serializable 对其进行了测试,如下所示:
导入java.io.*;
public class SerialazationDemo {
public static void main(String[] args) {
//serialized object
/* 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("E:\\temp\\employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}*/
//deserialized object
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("E:\\temp\\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);
}
}
class Employee {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
我发现 jvm 给出的异常为 java.io.NotSerializableException 但是文件是在给定的路径上创建的,类似的反序列化异常。那么为什么JVM要求它被序列化,它可以直接允许创建一个序列化。?