當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java NotSerializableException用法及代碼示例


Java 中的序列化是將對象的狀態寫入byte-stream 的機製。主要應用於Hibernate、RMI、JPA、EJB、JMS技術。

序列化的逆操作稱為反序列化,其中byte-stream被轉換為對象。序列化和反序列化過程是平台無關的,這意味著您可以在一個平台上序列化對象,並在不同平台上反序列化它。

在 Java 中,當類的實例必須實現 Serialized 接口時,會引發 NotSerializableException 異常。異常是由序列化運行時或類的實例引發的。 NotSerializableException 的參數是類的名稱。

NotSerializableException 類擴展了 ObjectStreamException 類,該類被定義為特定於 Object Stream 類的所有異常的超類。此外,ObjectStreamException 類擴展了 IOException,它表示發生了 I/O 異常。

示例:

java.io
Class NotSerializableException
    java.lang.Object
        java.lang.Throwable
            java.lang.Exception
                java.io.IOException
                    java.io.ObjectStreamException
                        java.io.NotSerializableException

Note: All Implemented Interfaces are Serializable interface

用法:

public class NotSerializableException 
extends ObjectStreamException

在開始之前讓我們討論一下這個類的構造函數

  1. NotSerializableException():構造一個NotSerializableException對象。
  2. NotSerializedException(String classname):使用消息字符串構造NotSerializableException對象。

示例 1:

Java


// Java Program to Illustrate NotSerializableException
// Where Exception Is Thrown
// Importing required classes
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
// Class 1
// Helper class
class Employee {
    // Member variables
    private String id;
    // Member methods
    // Method 1
    // To get ID of an employee
    public String getId() { return id; }
    // Method 1
    // To set ID of an employee
    public void setId(String id)
    {
        // this keyword refers to current object itself
        this.id = id;
    }
}
// Class 2
// Main Class
public class GFG {
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        // Create FileOutputStream class object  to
        // create a file
        FileOutputStream out
            = new FileOutputStream("employee.dat");
        // Similarly creating ObjectOutputStream class
        // object
        ObjectOutputStream outputStream
            = new ObjectOutputStream(out);
        // Creating objects of class 1
        Employee obj = new Employee();
        // Assifning ID to an employee
        obj.setId("001");
        // Writing objects to stream
        outputStream.writeObject(obj);
        // Good practice is always to
        // Close the stream using close() method
        outputStream.close();
    }
}


輸出:

Errors in Code
Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "employee.dat" "write")
at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
at java.base/java.security.AccessController.checkPermission(AccessController.java:897)
at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)
at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:225)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:126)
at NotSerializableExceptionExample.main(NotSerializableExceptionExample.java:21)                                                    

如何處理NotSerializableException

  • 最簡單的解決方案是找到拋出異常的類並使其實現 Serialized 接口。但是,如果引發異常的類屬於第三方庫,則這可能不可行。
  • 如果類引用不可序列化的對象並且這些對象不應被序列化,則可以將這些對象聲明為瞬態對象。一旦類的字段被聲明為瞬態,那麽它就會被可序列化運行時忽略。

示例 2:

Java


// Java Program to Illustrate NotSerializableException
// where No Exception is Thrown Using Serializable interface
// Importing input output class
import java.io.Serializable;
// By implementing Serializable interface
// we are allowing Student object to
// be stored in TestFile.txt
// Class 1
// Helper class extending to Serializable interface
class Student implements Serializable {
    // Member variables of this class
    int id;
    String name;
    // Constructor of this class
    public Student(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
}
// Class 2
// Main class
class Persist {
    // Main driver method
    public static void main(String args[])
    {
        // try block to check for exceptions
        try {
            // Creating the object
            Student s1 = new Student(007, "Test");
            // Creating stream and writing the object
            FileOutputStream fout
                = new FileOutputStream("TestFile.txt");
            ObjectOutputStream out
                = new ObjectOutputStream(fout);
            out.writeObject(s1);
            out.flush();
            // Closing the stream to free up memory space
            // using close() method
            out.close();
            // Display command to shown proper execution of
            // a program
            System.out.println(
                "Object stored successfully");
        }
        // Catch block to handle the exceptions
        catch (Exception e) {
            // Print and display the exception on the
            // console
            System.out.println(e);
        }
    }
}



輸出:

Object stored successfully


相關用法


注:本文由純淨天空篩選整理自praveen13kulkarni大神的英文原創作品 NotSerializableException in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。