第三方图形库中的NotSerializableException

时间:2019-04-15 20:53:49

标签: java exception serialization libraries notserializableexception

我使用 ACM图形库创建了Atari Breakout游戏的克隆版本,并刚刚添加了高分界面和功能。玩家的姓名和分数应显示在GUI窗口上(成功显示),并且还应写入.dat二进制文件中。

但是,当代码尝试加载现有文件时,出现以下错误。

writing aborted; java.io.NotSerializableException: acm.graphics.GCanvasListener

我已经在线研究了此错误,看来可以通过编辑该类以实现Serializable 来解决。但是,引发此错误的类不是我自己的,而是属于第三方ACM图形库的类。我该如何解决?

我什至不确定为什么首先要导致此错误,因为我尝试序列化的数据只是名称和得分,我不是在尝试序列化物体或类似物体的画布。

主类(称为Breakout)

public class Breakout extends GraphicsProgram {
    ... // game variables
    public void run() {
        ... // this if clause runs when game ends
        if (brickCounter > 0) {
                removeAll(); // clears screen
                printGameOver(); // displays game over message
                HighscoreManager hm = new HighscoreManager();
                String name = getHighScoreName();
                hm.addScore(name, score);
                hm.displayHighscores();
        }
    }
    ... // game functionality methods
    private String getHighScoreName(){
        IODialog dialog = new IODialog();
        String name = dialog.readLine("Enter your name: ");
        return name;
    }

得分班

private class Score implements Serializable {
    private int score;
    private String name;

    public Score(String name, int score) {
        this.score = score;
        this.name = name;
    }

    public int getScore() { return score; }
    public String getName() { return name; }
}

ScoreComparator类

private class ScoreComparator implements Comparator<Score> {
    public int compare(Score score1, Score score2) {

        int sc1 = score1.getScore();
        int sc2 = score2.getScore();

        if (sc1 > sc2) {
            return -1;
        } else if (sc1 < sc2) {
            return 1;
        } else {
            return 0;
        }
    }
}

HighscoreManager类

private class HighscoreManager {
    private ArrayList<Score> scores;
    private static final String HIGHSCORE_FILE = ".//bin//scores.dat";
    ObjectOutputStream outputStream = null;
    ObjectInputStream inputStream = null;

    public HighscoreManager() {
        scores = new ArrayList<Score>(10);
    }

    public ArrayList<Score> getScores() {
        loadScoreFile();
        sort();
        return scores;
    }

    private void sort() {
        ScoreComparator comparator = new ScoreComparator();
        Collections.sort(scores, comparator);
    }

    public void addScore(String name, int score) {
        loadScoreFile();
        scores.add(new Score(name, score));
        updateScoreFile();
    }

    public void loadScoreFile() {
        try {
            inputStream = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE));
            scores = (ArrayList<Score>) inputStream.readObject();
        }
        catch (FileNotFoundException e) {
            System.out.println("[Load] File Not Found Error: " + e.getMessage());
        }
        catch (IOException e) {
            System.out.println("[Load] Input/Output Error: " + e.getMessage());
        }
        catch (ClassNotFoundException e) {
            throw new RuntimeException("[Load] Class Not Found Error: " + e.getMessage());
        }
        finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                System.out.println("[Load] Input/Output Error: " + e.getMessage());
            }
        }
    }

    public void updateScoreFile() {
        try {
            outputStream = new ObjectOutputStream(new FileOutputStream(HIGHSCORE_FILE));
            outputStream.writeObject(scores);
        }
        catch (FileNotFoundException e) {
            System.out.println("[Update] File Not Found Error: " + e.getMessage());
        }
        catch (IOException e) {
            System.out.println("[Update] Input/Output Error: " + e.getMessage());
        }
        finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                System.out.println("[Update] Input/Output Error: " + e.getMessage());
            }
        }
    }

    public void displayHighscores() {
        int max = 10;
        ArrayList<Score> scores;
        scores = getScores();
        int x = scores.size();

        if (x > max) {
            x = max;
        }

        removeAll(); // clears screen
        int npos = 160;
        int spos = 160;

        for (int i = 0; i < x; i++) {
            GLabel showName = new GLabel(scores.get(i).getName(), (getWidth() / 2.0) - 100, (getHeight() / 2.0) - npos);
            showName.move(-showName.getWidth() / 2, -showName.getHeight());
            showName.setColor(Color.WHITE);
            add(showName);
            npos -= 40;
        }

        for (int i = 0; i < x; i++) {
            GLabel showScore = new GLabel(Integer.toString(scores.get(i).getScore()), (getWidth() / 2.0) + 100, (getHeight() / 2.0) - spos);
            showScore.move(-showScore.getWidth() / 2, -showScore.getHeight());
            showScore.setColor(Color.WHITE);
            add(showScore);
            spos -= 40;
        }
    }

运行应用程序后:

[Load] Input/Output Error: writing aborted; java.io.NotSerializableException: acm.graphics.GCanvasListener
[Update] Input/Output Error: acm.graphics.GCanvasListener
[Load] Input/Output Error: writing aborted; java.io.NotSerializableException: acm.graphics.GCanvasListener

2 个答案:

答案 0 :(得分:0)

您应该进入名称得分字段所在的班级,并添加例如public class nameclass implements Serializable。我希望它对您有用。

答案 1 :(得分:0)

您的任务将是从您的姓名和分数结构中找到UI组件的隐藏引用。许多GUI应用程序使用许多内部类,这可能是缺少的链接。

当你上课时,像这样:

class MyGame {
    private SomeUIWidget widget;
    class TopScore implements Serializable {
        String name;
        int score;
        ...
    }
    ...
}

TopScore中有一个隐藏的成员,它引用MyGame的“封闭实例”,包括其SomeUIWidget成员。当您尝试序列化TopScore实例时,其余所有实例都将被拖入其中。

您可以简单地将TopScore声明为static嵌套类。这意味着没有封闭的实例,仅用于从其他代码隐藏TopScore类。但是,我建议仅在自己的文件中将TopScore设为一个顶级类,因为其他对象很可能希望以不同的方式使用这些对象,也就是说,似乎很可能成为该对象的候选对象您的公共API。

这是有根据的猜测,没有任何实际的代码。为了获得更好的答案,请将代码减少到演示问题所需的最低限度,并将其包含在问题中。