作用:
体现在将数据序列化的时候,你不想把其中的某个属性序列化到文件中,就需要用transient修饰,指明该属性是一个临时的属性
相关java视频教程:java免费视频教程
这是一个学生类:
public class student implements serializable {//注意:要想序列化,必须实现serializable接口 private string name; private integer age; private transient string address; //使用transient修饰 public student() { } public student(string name, integer age, string address) { this.name = name; this.age = age; this.address = address; } //getter/setter}
我序列化的时候不打算将学生的地址这个属性保存,只想保存name和age属性,我将adress属性用transient关键字修饰,下面进行序列化:
public class teststudent { public static void main(string[] args) throws ioexception { list<student> list = new arraylist<>(); student s1 = new student("jack", 20, "北京"); student s2 = new student("rose", 21, "上海"); student s3 = new student("hoke", 22, "深圳"); student s4 = new student("mark", 23, "天津"); student s5 = new student("json", 24, "成都"); list.add(s1); list.add(s2); list.add(s3); list.add(s4); list.add(s5); //将学生信息序列化到student.txt文件中 file file = new file("student.txt"); objectoutputstream oos = new objectoutputstream(new fileoutputstream(file)); oos.writeobject(list); }}
下面进行反序列化,进行验证transient的作用:
@test public void test() throws ioexception, classnotfoundexception { objectinputstream ois = new objectinputstream(new fileinputstream(new file("student.txt"))); object object = ois.readobject(); if (object instanceof list) { list<student> list = (list<student>) object; list.foreach(system.out::println); } }
结果:
可以看到输出结果中的address属性值为null,没有将值序列化进去;
java相关文章教程:java零基础入门
以上就是java中的transient关键字有什么作用的详细内容。