dubbo接口中,传递的对象都是implements Serializable 接口的。今天改bug,我不小心把对象中的参数类型改了报错了。
将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时,读出/写入都没有问题。
写入与读出类型不一致时,就会报错(java.io.InvalidClassException: com.demo.Person; incompatible types for field age)。
时间长了,忘记了包装类与基本类型的区别了。