transient关键字【英文意思:短暂的;反义词:persistent持久的,持久化的】
2)transient关键字只能修饰变量,而不能修饰方法和类。注意,本地变量是不能被transient关键字修饰的。变量如果是用户自定义类变量,则该类需要实现Serializable接口。
3)被transient关键字修饰的变量不再能被序列化,一个静态变量不管是否被transient修饰,均不能被序列化。
1)一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法获得访问。
已经通过代码测试,如下:
package concurrentHashMapDemo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class TestTransient implements Serializable{
private static final long serialVersionUID = 1L;
private String name = "abcdefg";
private transient String pwd = "123456";
public static void main(String[] args) throws IOException {
File file = new File("D:"+File.separator+"ydx.txt");
TestTransient tt = new TestTransient();
FileOutputStream fos=new FileOutputStream(file);
fos.write(ObjectToByte(tt));
fos.flush();
fos.close();
}
public static byte[] ObjectToByte(java.lang.Object obj) {
byte[] bytes = null;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch (Exception e) {
System.out.println("translation" + e.getMessage());
e.printStackTrace();
}
return bytes;
}
}
2)transient关键字只能修饰变量,而不能修饰方法和类。注意,本地变量是不能被transient关键字修饰的。变量如果是用户自定义类变量,则该类需要实现Serializable接口。
3)被transient关键字修饰的变量不再能被序列化,一个静态变量不管是否被transient修饰,均不能被序列化。