- package com.jd;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.util.Date;
- public class App {
- public static void main(String[] args) {
- //现在我们创建一个类的实例,并且串行化(serialize)它,然后将这个串行化对象写入磁盘
- LoggingInfo logInfo = new LoggingInfo("MIKE", "MECHANICS");
- System.out.println(logInfo.toString());
- try {
- ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("logInfo.out"));
- o.writeObject(logInfo);
- o.close();
- } catch (Exception e) {
- }
- //读出上面写入文件中的串行化对像,发现transient标识的pwd属性值并不会被存储
- try {
- ObjectInputStream in = new ObjectInputStream(
- new FileInputStream("logInfo.out"));
- logInfo = (LoggingInfo) in.readObject();
- System.out.println(logInfo.toString());
- }
- catch (Exception e) {
- }
- }
- static class LoggingInfo implements java.io.Serializable {
- private Date loggingDate = new Date();
- private String uid;
- private transient String pwd;
- LoggingInfo(String user, String password) {
- uid = user;
- pwd = password;
- }
- public String toString() {
- String password = null;
- if (pwd == null) {
- password = "NOT SET";
- } else {
- password = pwd;
- }
- return "logon info: \n " + "user: " + uid +
- "\n logging date : " + loggingDate.toString() +
- "\n password: " + password;
- }
- }
- }
总之,transient关键字是为了安全性,防止这种类型的数据在IO中存储(例如网络传输或本地存盘)
阅读(2753) | 评论(0) | 转发(1) |