Java中Serializable接口的用法

今天学习了Serializable接口的用法,以及

private static final long serialVersionUID的具体用法

如下

如果今天你的类Serialized存到硬盘里,
可是後来你却更改了类别的field(增加或减少或改名).
当你Deserialize时,就会出现Exception.这样就会做成不兼容性的问题.
但当serialVersionUID相同时,它就会将不一样的field以type的预设值Deserialize.
这个可以避开不兼容性的问题.

例子:

public class User implements Serializable {

private static final long serialVersionUID = -7020619477594468968L;

 

private String name;

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

}

User类实现了serializable接口,里面有一个name域。

public class SerialzeTest {

 

public static void main(String[] args)

{

try {

File test = new File("test.seri");

FileOutputStream out = new FileOutputStream(test);

ObjectOutputStream oout = new ObjectOutputStream(out);

User user = new User();

user.setName("example1");

oout.writeObject(user);

FileInputStream in = new FileInputStream(test);

ObjectInputStream oin = new ObjectInputStream(in);

User user = (User)oin.readObject();

System.out.println(user.getName());

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

}

该类将User类输入到test.seri文件中,再从中读取出来。

假如现在将User类改变

public class User implements Serializable {

 

 

private static final long serialVersionUID = -7020619477594468968L;

 

private String name;

 

private String pass;

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

public String getPass() {

return pass;

}

 

public void setPass(String pass) {

this.pass = pass;

}

}

添加了一个password域,这里并没有改变serialVersionUID

再使用serialtest类

 

public class SerialzeTest {

 

public static void main(String[] args)

{

try {

File test = new File("test.seri");

// FileOutputStream out = new FileOutputStream(test);

// ObjectOutputStream oout = new ObjectOutputStream(out);

// User user = new User();

// user.setName("example1");

// oout.writeObject(user);

FileInputStream in = new FileInputStream(test);

ObjectInputStream oin = new ObjectInputStream(in);

User user = (User)oin.readObject();

System.out.println(user.getName());

System.out.println(user.getPass());

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

}

从test.seri文件中读取该类就不会抛出异常,输出为

example1

null

即会将password域认为空。

假如在新的User类中修改了serialVersionUID值,就会抛出异常

你可能感兴趣的:(java)