序列化问题
程序员文章站
2022-04-03 12:29:03
...
package interview.serializable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import junit.framework.TestCase;
public class InnerSerialDemo extends TestCase implements Serializable
{
public void testSerial()
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(new Student("xiaolong", 23));
}
catch (IOException e)
{
e.printStackTrace();
}
assertTrue(bos.toByteArray().length > 0);
}
// 如果是非静态类,则外部类必须serailizable
// 如果是静态内部类,则外部不需要
private class Student implements Serializable
{
private String name;
// 不被序列化的字段
transient private int age;
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return "name=" + this.name + ",age=" + this.age;
}
}
}