transient用法示例
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
/**
* 类实现序列化接口,设置某一个属性不要序列化
* @author mapeijie
*/
public class Transient implements Serializable {
private static final long serialVersionUID = -8332293766575736513L;
private String username;
private Date date = new Date();
private transient String password;
public Transient(String name, String pwd) {
username = name;
password = pwd;
}
@Override
public String toString() {
String pwd = (password == null) ? "(n/a)" : password;
return "Logon [username=" + username + ", date=" + date + ", password=" + pwd + "]";
}
public static void main(String[] args) {
Transient a = new Transient("Hulk", "passwd");
System.out.println("logon a = " + a);
try {
//write
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("Logon.out"));
o.writeObject(a);
o.close();
//wait
int seconds = 10;
long t = System.currentTimeMillis() + seconds * 1000;
while (System.currentTimeMillis() < t);
// Now get them back:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("Logon.out"));
System.out.println("Recovering object at " + new Date());
a = (Transient) in.readObject();
System.out.println("logon a = " + a);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
/**
* 实现序列化接口,设置某一个属性不要序列化
* @author mapeijie
*/
public class Transient implements Serializable {
private static final long serialVersionUID = -8332293766575736513L;
private String username;
private Date date = new Date();
private transient String password;
public Transient(String name, String pwd) {
username = name;
password = pwd;
}
@Override
public String toString() {
String pwd = (password == null) ? "(n/a)" : password;
return "Logon [username=" + username + ", date=" + date + ", password=" + pwd + "]";
}
public static void main(String[] args) {
Transient a = new Transient("Hulk", "passwd");
System.out.println("logon a = " + a);
try {
//write
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("Logon.out"));
o.writeObject(a);
o.close();
//wait
int seconds = 10;
long t = System.currentTimeMillis() + seconds * 1000;
while (System.currentTimeMillis() < t);
// Now get them back:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("Logon.out"));
System.out.println("Recovering object at " + new Date());
a = (Transient) in.readObject();
System.out.println("logon a = " + a);
} catch (Exception e) {
e.printStackTrace();
}
}
}