在看java.util.ArrayList这个类的源码时,发现其中有个成员变量Object[] elementData 被transient修饰了。突然脑袋回忆不起这个关键字的具体用法了,只知道被此关键字修饰的成员变量不会被序列化。于是我查阅了一下资料。
当一个类实现了Serializable接口后,那么他就是可被序列化的。一个继承了可序列化类的类本身也是可别序列化的。(源码描述:
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. All subtypes of a serializable class are themselves serializable.
)
在一个可被序列化的类中:
1.transient只能修饰成员变量/类变量,被它修饰的成员变量将不能被序列化(类变量无论是否被transient修饰都无法被序列化)
2.如果成员变量是自定义对象类型,那么也必须是可序列化的。如果不是,则可以通过transient修饰,否则会报java.io.NotSerializableException异常。
测试:
1 package com.test; 2 import java.io.*; 3 public class TestTransient { 4 5 public static void main(String[] args) throws IOException, ClassNotFoundException { 6 User user = new User(); 7 user.setPassword("password"); 8 user.setUsername("jery"); 9 person p = new person();10 p.setName("tom");11 p.setAge(12);12 user.setPerson(p);13 14 ByteArrayOutputStream bos = new ByteArrayOutputStream();15 ObjectOutputStream os = new ObjectOutputStream(bos);16 os.writeObject(user);17 // user.setUsername("yiiiy"); 测试username被static修饰后,是否会被序列化18 byte[] bytes = bos.toByteArray();19 ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(bytes));20 User u = (User) is.readObject();21 System.out.println(u);22 }23 }24 25 class User implements Serializable{26 private String username;27 private String password;28 transient person person;29 30 public com.common.util.person getPerson() {31 return person;32 }33 34 public void setPerson(com.common.util.person person) {35 this.person = person;36 }37 38 public String getUsername() {39 return username;40 }41 42 public void setUsername(String username) {43 this.username = username;44 }45 46 public String getPassword() {47 return password;48 }49 50 public void setPassword(String password) {51 this.password = password;52 }53 54 @Override55 public String toString() {56 return "User{" +57 "username='" + username + '\'' +58 ", password='" + password + '\'' +59 ", person=" + person +60 '}';61 }62 }63 64 class person{65 private String name;66 private Integer age;67 68 public String getName() {69 return name;70 }71 72 public void setName(String name) {73 this.name = name;74 }75 76 public Integer getAge() {77 return age;78 }79 80 @Override81 public String toString() {82 return "person{" +83 "name='" + name + '\'' +84 ", age=" + age +85 '}';86 }87 88 public void setAge(Integer age) {89 this.age = age;90 }91 }