java中transient关键字的作用

发布时间:2020-06-24 10:30:35 作者:Leah
来源:亿速云 阅读:267

这期内容当中的小编将会给大家带来有关java中transient关键字的作用,以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

作用:

体现在将数据序列化的时候,你不想把其中的某个属性序列化到文件中,就需要用transient修饰,指明该属性是一个临时的属性

这是一个学生类:

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);
        }
    }

结果:

java中transient关键字的作用

可以看到输出结果中的address属性值为null,没有将值序列化进去;

上述就是小编为大家分享的java中transient关键字的作用了,如果您也有类似的疑惑,不妨碍参照上述分析进行理解。如果想了解更多相关内容,请关注亿速云行业资讯。

推荐阅读:
  1. java中不同注解的作用
  2. java中的transient关键字怎么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java transient

上一篇:SQUID代理服务器(1)

下一篇:用pycharm如何调出工具栏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》