java中对象的序列化问题

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)。

时间长了,忘记了包装类与基本类型的区别了。

 

 

转载于:https://my.oschina.net/u/2345654/blog/994563

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值