考慮下面的代碼:NotSerializableException異常總是出現(爪哇) - 序列化將無法工作
import java.io.*;
public class Main {
public static void main(String argv[]) throws IOException
{
View view = null;
try
{
/* Open the file that is the first command line parameter
text file must be inside the project library , not in the src library */
FileInputStream fstream = new FileInputStream("input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader groupsFile = new BufferedReader(new InputStreamReader(in));
view = new View();
view.insertTeamsFromFile(groupsFile);
view.startCompetition();
in.close();
}
//Catch exception if any
catch (Exception e) { System.err.println("Error: " + e.getMessage()); }
try
{
String filename = "view.txt";
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(view);
out.close();
System.out.println("Object Persisted");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
當我站上罰球線out.writeObject(view);
的NotSerializableException appears.The查看對象包括一些其他的對象,我從該代碼中的文件讀取輸入。假設View對象被創建得很好,這裏可能是什麼問題?
View class :
public class View implements Serializable {
import java.io.*;
import java.util.*;
/* Constructor */
private Controller controller;
public View()
{
controller = new Controller();
}
... ...
// more code
}
的確切消息是:
java.io.NotSerializableException: core.Controller
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
有什麼不對嗎?
問候,羅恩
那麼,是'core.Controller'可序列化?似乎不是。你爲什麼對這個例外感到驚訝? – Mat 2012-01-01 11:44:20
錯誤消息已足夠清晰。 'Controller'類也必須實現'Serializable'。事實上,View的每個類都有一個字段,每個類都有一個類作爲一個字段,等等貫穿整個層次,必須實現'Serializable'(或者聲明爲'transient')或者你會得到一個類似的錯誤信息。 – aroth 2012-01-01 11:46:21