【发布时间】:2012-01-19 00:28:20
【问题描述】:
我正在尝试在我的程序中序列化我的模型。该模型被命名为“ImageModel”,它实现了Serializable。此模型还包含另一个名为“Perspective”的自定义对象,它也实现了Serializable。我有一个静态实用程序类,可以序列化我的模型并读取它。此代码已在 main 方法中使用“ImageModel”进行了测试,一切正常。
但是当我尝试在实际程序中使用它时,我遇到了问题。 “ImageModel”类在我的系统类中声明,命名为“MainWindow”,它扩展了JFrame,是大多数不同类之间的链接。出于某种原因,我无法序列化模型执行MainWindow.getModel() 之类的操作。编译器认为我的“EventFactory”不可序列化。这个类也在“MainWindow”中声明,但我什至不明白Java为什么要序列化它,我的印象是java不仅要序列化模型,还要序列化GUI。
以下是代码段:
我的模特:
public class ImageModel extends Observable implements Cloneable, Serializable {
private String path;
private ArrayList<Observer> observers;
private ArrayList<Perspective> perspectives;
private int numPerspectives;
private Perspective selectedPerspective;
...
}
透视类:
public class Perspective implements Serializable {
private ImageModel image;
private int degreeOfRotation;
private Point topLeftPoint;
private int zoomPercentage;
private int height;
private int width;
...
}
声明模型和其他元素的实际 GUI:
public class MainWindow extends JFrame {
private final int GRID_ROWS = 0;
private final int GRID_COLUMNS = 2;
private final int NUM_PERSPECTIVE = 3;
private JPanel mainPane;
private ArrayList<View> perspectiveList;
private ImageModel imageModel;
private EventFactory eventFactory;
private JMenu menu;
private JToolBar toolBar;
...
}
main 方法:
MainWindow mw = new MainWindow();
/*
* Does NOT work:
* ImageModel imageModel= mw.getImageModel();
* Utility.serializeModel(imageModel); //Crashes
*
* Works:
*
* ImageModel imageModel= new ImageModel();
* Utility.serializeModel(imageModel);
*
*/
这是我的两个实用功能,以备您需要时使用:
public static void serializeModel(ImageModel imageModel)
{
String filename = "TEST.ser";
FileOutputStream fos = null;
ObjectOutputStream out = null;
try
{
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(imageModel);
out.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public static ImageModel restoreModel(String filename)
{
ImageModel imageModel = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try
{
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
imageModel = (ImageModel)in.readObject();
in.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return imageModel;
}
这是我在处理实际用例时收到的错误的 STACK_TRACE:
是的,就像我说的那样,就像 Java 试图序列化模型周围的其他东西一样。
【问题讨论】:
-
不是真正的答案,但如果您想解决它:将 EventFactory 更改为瞬态数据成员。例如:“私有瞬态 EventFactory eventFactory;”
-
1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) 至少将堆栈跟踪的前 50 行左右直接放在问题中。大多数人不会点击链接。
标签: java swing ioexception serializable