[英]java.io.NotSerializableException with ObjectOutputStream
[英]java.io.NotSerializableException by ObjectOutputStream.write Object
我有一個要寫入File的對象:
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,使SwingUtilities.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);
}
});
然后出現異常
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”而不會出現異常,然后我就永遠不會遇到這個問題。
解決了。
我有PersonDaten作為內部類。
讓PersonDaten成為自己的班級並且沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.