java.io.NotSerializableException由ObjectOutputStream.写作对象



我有一个对象,我想写在文件:

class PersonDaten implements Serializable {
    private static final long serialVersionUID = 1L;
    String firstname = "";
    Sting lastname = "";    
}
class InputOutput {
    public static <T> void output(T daten, String datei){
        try {
            FileOutputStream fout = new FileOutputStream(datei);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(daten);
            oos.close();
        }
        catch (Exception e) { e.printStackTrace(); }
    }
}

和我有一个Runnable,与反射工作,使swingutility . invokelater()只有1次。

public class UpdateRoutine implements Runnable, Serializable {
    private static final long serialVersionUID = 1L;
    List<Map.Entry<Method, Object[]>> updates;
    public UpdateRoutine(){
        updates = new ArrayList<Map.Entry<Method, Object[]>>();
    }
    @Override
    public void run() {
        for(int i = 0; i < updates.size(); i++){
            Entry<Method, Object[]> m = updates.get(i);
            Object[] values = m.getValue();
            try {
                if(values.length == 1){
                    m.getKey().invoke(values[0]);
                }
                else if(values.length == 2){
                    m.getKey().invoke(values[0], values[1].getClass().cast(values[1]));
                }
                else if(values.length == 3){
                    m.getKey().invoke(values[0], values[1].getClass().cast(values[1]), 
                            values[2].getClass().cast(values[2]));
                }
                else if(values.length == 4){
                    m.getKey().invoke(values[0], values[1].getClass().cast(values[1]), 
                            values[2].getClass().cast(values[2]), values[3].getClass().cast(values[3]));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                System.out.println(m.getKey() + " " + values[0]);
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
    public void addToUpdate(Method m, Object[] args){
        Entry<Method, Object[]> se = new SimpleEntry<Method, Object[]>(m, args);
        updates.add(se);
    }
}

通过关闭Main

中的应用程序调用
addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent windowEvent) {
        userDaten.save();
        System.exit(0);
    }
});

然后是Exception

java.io.NotSerializableException: java.lang.reflect.Method
at util.InputOutput.output(InputOutput.java:40)
at training.Person.save(Person.java:55)
at ui.Main$1.windowClosing(Main.java:105)

此异常仅在第一次运行时"File.dat"不存在时出现。如果我在第一次运行应用程序时不使用UpdateRoutine,"File.dat"可以毫无例外地保存,然后我就不会有这个问题了。

  1. PersonDaten没有导入java.lang.reflect.Method为什么会出现这个例外?
  2. 如何避免此异常?

已解析

我把PersonDaten作为内部类。

把PersonDaten设为自己的类,没有问题

最新更新