Java中transient有何作用?

來源:互聯網
上載者:User

標籤:

  transient關鍵字用來防止序列化域。如果一個參考型別被transient修飾,則其還原序列化的結果是null。基本類型則為0。如果參考型別時不可序列化的類,則也應該使用transient修飾,它在還原序列化時會被直接跳過。

可以用transient來修飾不想儲存的域

下面的例子可以看到被transient修飾的name,使用序列化複製後,還原序列化的結果是null

package com.lk.B;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class Employee implements Cloneable,Serializable{private static final long serialVersionUID = 1L;private transient String name;private int age;public Employee(String name,int age){this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {// TODO Auto-generated method stubStringBuffer sb = new StringBuffer();sb.append("姓名:"+name+",");sb.append("年齡:"+age+"\n");return sb.toString();}@Overrideprotected Employee clone() {// TODO Auto-generated method stubEmployee employss = null;ByteArrayOutputStream baos = new ByteArrayOutputStream();try {ObjectOutputStream oos = new ObjectOutputStream(baos);oos.writeObject(this);oos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());try {ObjectInputStream ois = new ObjectInputStream(bais);employss = (Employee) ois.readObject();ois.close();} catch (IOException | ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return employss;}}

  

package com.lk.B;public class Test3 {    public static void main(String[] args) {        Employee emp = new Employee("阿坤", 21);        System.out.println(emp);        Employee emp1 = emp.clone();        System.out.println(emp1);    }}
姓名:阿坤,年齡:21姓名:null,年齡:21

 

Java中transient有何作用?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.