Java中的transient关键字介绍
程序员文章站
2024-03-02 15:20:34
transient说明一个属性是临时的,不会被序列化。
下面是一个demo,name声明为 transient,不被序列化
package com.zzs.t...
transient说明一个属性是临时的,不会被序列化。
下面是一个demo,name声明为 transient,不被序列化
package com.zzs.tet; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.objectinput; import java.io.objectinputstream; import java.io.objectoutput; import java.io.objectoutputstream; import java.io.serializable; public class transientdemo implements serializable{ /** * */ private static final long serialversionuid = 1l; private transient string name; private string password; public string getname() { return name; } public void setname(string name) { this.name = name; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } /** * @param args * @throws ioexception * @throws filenotfoundexception * @throws classnotfoundexception */ public static void main(string[] args) throws filenotfoundexception, ioexception, classnotfoundexception { // todo auto-generated method stub string path="d:"+file.separator+"object.txt"; file file=new file(path); transientdemo transientdemo=new transientdemo(); transientdemo.setname("姓名"); transientdemo.setpassword("密码"); objectoutput output=new objectoutputstream(new fileoutputstream(file)); output.writeobject(transientdemo); objectinput input=new objectinputstream(new fileinputstream(file)); transientdemo demo=( transientdemo )input.readobject(); system.out.println(demo.getname()+demo.getpassword()); } }
输出结果:
null密码