dubbo接口中,傳遞的對象都是implements Serializable 接口的。今天改bug,我不當心把對象中的參數類型改了報錯了。java
將person對象寫進文件中作測試。測試
package com.demo; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private String address; private Integer age; private int status = 0; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
package com.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; public class Test { private static File file = new File("obj.txt"); public static void main(String[] args) { /*Person p1 = new Person(); p1.setName("李四"); p1.setAge(89); writeToFile(p1, file);*/ Object obj = readToFile(file); Person p = (Person) obj; System.out.println(p.getAge()); } public static void writeToFile(Object obj, File file){ OutputStream out = null; ObjectOutputStream oos = null; try { out = new FileOutputStream(file); oos = new ObjectOutputStream(out); oos.writeObject(obj); oos.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ if(oos!=null){ try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } if(out!=null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static Object readToFile(File file){ Object obj = null; FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); obj = ois.readObject(); } catch (Exception e) { e.printStackTrace(); }finally{ if(fis!=null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(ois!=null){ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return obj; } }
person的age都爲Integer或int時,讀出/寫入都沒有問題。this
寫入與讀出類型不一致時,就會報錯(java.io.InvalidClassException: com.demo.Person; incompatible types for field age)。.net
時間長了,忘記了包裝類與基本類型的區別了。code