我对静态变量的序列化有点困惑,因为它们不能序列化。虽然singleton类对象可以序列化。 我有一个示例代码:
TestSerilization
类中:我首先编译了一个运行代码而没有
评论我得到了结果,但正如我评论部分并重新编译
并运行我没有获得静态字符串值的所需结果
而反序列化在TestSerilization2
类中:我首先编译运行代码没有注释我得到了结果,但是当我评论部分和
重新编译和运行我确实得到了私有静态相同的结果
反序列化时的学生实例值。
我想问一下为什么private static Student
实例提供了值但私有static String name
没有,尽管两者都是static
。
import java.io.*;
class Student implements Serializable{
private static String name;
private int rollNo;
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setRollNo(int rollNo){
this.rollNo=rollNo;
}
public int getRollNo(){
return this.rollNo;
}
}
public class TestSerilization{
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException{
/*
Student s1=new Student();
s1.setName("Apoorv");
s1.setRollNo(13);
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:\\JAVA Practice\\output.ser"));
oos.writeObject(s1);
System.out.println("s1: name-"+s1.getName()+" rollno-"+s1.getRollNo()+" hascode: "+s1.hashCode());
*/
ObjectInputStream ins=new ObjectInputStream(new FileInputStream("D:\\JAVA Practice\\output.ser"));
Student s2=(Student)ins.readObject();
System.out.println("s2: name-"+s2.getName()+" rollno-"+s2.getRollNo()+" hascode: "+s2.hashCode());
}
}
import java.io.*;
final class Student implements Serializable{
private static Student instance;
private String name;
private int rollNo;
private Student(){}
public static Student getInstance(){
if(instance==null){
instance=new Student();
}
return instance;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setRollNo(int rollNo){
this.rollNo=rollNo;
}
public int getRollNo(){
return this.rollNo;
}
}
public class TestSerilization2{
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException{
/*
Student s1=Student.getInstance();
s1.setName("Apoorv");
s1.setRollNo(13);
System.out.println("s1: name-"+s1.getName()+" rollno-"+s1.getRollNo()+" hascode: "+s1.hashCode());
Student s2=Student.getInstance();
System.out.println("s2: name-"+s2.getName()+" rollno-"+s2.getRollNo()+" hascode: "+s2.hashCode());
*/
/*
Student s1=Student.getInstance();
s1.setName("Apoorv");
s1.setRollNo(13);
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:\\JAVA Practice\\output2.ser"));
oos.writeObject(s1);
System.out.println("s1: name-"+s1.getName()+" rollno-"+s1.getRollNo()+" hascode: "+s1.hashCode());
*/
ObjectInputStream ins=new ObjectInputStream(new FileInputStream("D:\\JAVA Practice\\output2.ser"));
Student s2=(Student)ins.readObject();
System.out.println("s2: name-"+s2.getName()+" rollno-"+s2.getRollNo()+" hascode: "+s2.hashCode());
}
}