>  기사  >  Java  >  정적 변수를 직렬화할 수 없는 이유는 무엇입니까?

정적 변수를 직렬화할 수 없는 이유는 무엇입니까?

anonymity
anonymity원래의
2019-05-07 09:41:268685검색

정적 멤버는 클래스 수준에 속하므로 직렬화할 수 없습니다. 여기서 직렬화할 수 없다는 것은 직렬화된 정보에 이 정적 멤버 필드가 포함되어 있지 않음을 의미합니다

정적 변수를 직렬화할 수 없는 이유는 무엇입니까?#🎜🎜 #

정적 변수를 직렬화할 수 없는 이유를 보여주는 예는 다음과 같습니다.

Class Student1#🎜🎜 ##🎜 🎜#

package test;
 
import java.io.Serializable;
 
public class Student1 implements Serializable{
     private static final long serialVersionUID = 1L;
     private String name;
     private transient String password;
     private static int count = 0;
    
     public Student1(String name,String password){
    System.out.println("调用Student的带参构造方法 ");
    this.name = name;
    this.password = password;
    count++;
     }
    
     public String toString(){
    return "人数:" + count + "姓名:" + name + "密码:" + password;
     }
}
Class ObjectSerTest1

package test;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
public class ObjectSerTest1 {
     public static void main(String args[]){
    try{
    FileOutputStream fos = new FileOutputStream("test.obj");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    
    Student1 s1 = new Student1("张三","123456");
    Student1 s2 = new Student1("王五","56");
    
    oos.writeObject(s1);
    oos.writeObject(s2);
    
    oos.close();
    
    FileInputStream fis = new FileInputStream("test.obj");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Student1 s3 = (Student1) ois.readObject();
             Student1 s4 = (Student1) ois.readObject();
 
             System.out.println(s3);
             System.out.println(s4);
 
             ois.close();
         } catch (IOException e) {
             e.printStackTrace();
         } catch (ClassNotFoundException e1) {
             e1.printStackTrace();
         }
     }
}
실행 결과:

학생의 매개변수화된 생성자 메서드 호출#🎜🎜 #

매개변수로 학생 생성자 호출

인원: 2 이름: Zhang San 비밀번호: null

인원: 2 이름: Wang Wu 비밀번호: null#🎜 🎜## 🎜🎜#

Class Test1

package test;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
public class Test1{
 
    public static void main(String args[]){
        
        try {
 
            FileInputStream fis = new FileInputStream("test.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
 
            Student1 s3 = (Student1) ois.readObject();
            Student1 s4 = (Student1) ois.readObject();
 
            System.out.println(s3);
            System.out.println(s4);
 
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
    }    
}

실행 결과:

인원: 0 이름: Zhang San 비밀번호: null # 🎜🎜# 인원수: 0 이름: Wang Wu 비밀번호: null

Summary:

ObjectSerTest1 클래스의 실행 결과는 count=를 나타냅니다. 2, 직렬화된 것처럼 보이지만 Test1 클래스의 실행 결과를 보면 count=0이 직렬화되지 않은 것으로 나타납니다.

"직렬화는 객체의 상태를 저장하고 정적 변수는 클래스의 상태이므로 직렬화는 정적 변수를 저장하지 않습니다.

여기서의 의미는 직렬화되어 있으면 직렬화 정보에 이 정적 멤버 필드

ObjectSerTest1이 포함되어 있지 않습니다. jvm이 이미 개수를 로드했기 때문에 모두 동일한 시스템(및 동일한 프로세스)에 있으므로 테스트가 성공합니다. 그래서 얻을 수 있는 것은 로드된 카운트입니다. 다른 머신으로 전송하거나 프로그램을 닫고 다시 작성하고 test.obj를 읽는 프로그램을 작성하면 이때 다른 머신이나 새로운 프로세스가 카운트를 다시 로드하기 때문에 count 정보는 초기 정보입니다. "------ 참조 웹 페이지에서

Test1 클래스를 다시 작성하여 test.obj를 읽어서 표시되는 결과는 count의 초기 정보이며, 이 역시 위 내용을 확인합니다. 단락.

마지막으로 Java 객체의 정적 및 임시 수정 속성은 직렬화할 수 없습니다.

위 내용은 정적 변수를 직렬화할 수 없는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.