public class Test1 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
test();
}
static void test() throws IOException, ClassNotFoundException {
byte[] bytes;
/*在try(...)中的AutoCloseable类型的变量可以自动关闭*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
/*将一个实例序列化,获得其包含其字节信息的数组*/
oos.writeObject(new User());
oos.flush();
oos.close();
bytes = baos.toByteArray();
/*将字节信息反序列化为Java实例*/
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
Object o = ois.readObject();
ois.close();
}
}
/*被序列化的类需要实现java.io.Serializable接口,
并且其中未使用transient修饰的属性也应如此,才能确保序列化成功*/
class User implements Serializable {
private static final long serialVersionUID = 6836230847556332334L;
}
IDEA中生成SerialVersionUID
勾选如下选项
完成后把光标放在在实现Serializable接口的类名上按Alt+Enter
弹出的菜单中有一项名为 Add serialVersionUID field的选项,点击即可
牛哔!