Java transient关键字(序列化避免被反序列化获取敏感信息)
生活随笔
收集整理的這篇文章主要介紹了
Java transient关键字(序列化避免被反序列化获取敏感信息)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;/*** @description 使用transient關鍵字不序列化某個變量* 注意讀取的時候,讀取數據的順序一定要和存放數據的順序保持一致* * @author Alexia* @date 2013-10-15*/
public class TransientTest {public static void main(String[] args) {User user = new User();user.setUsername("Alexia");user.setPasswd("123456");System.out.println("read before Serializable: ");System.out.println("username: " + user.getUsername());System.err.println("password: " + user.getPasswd());try {ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("C:/user.txt"));os.writeObject(user); // 將User對象寫進文件os.flush();os.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}try {ObjectInputStream is = new ObjectInputStream(new FileInputStream("C:/user.txt"));user = (User) is.readObject(); // 從流中讀取User的數據is.close();System.out.println("\nread after Serializable: ");System.out.println("username: " + user.getUsername());System.err.println("password: " + user.getPasswd());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}
}class User implements Serializable {private static final long serialVersionUID = 8294180014912103005L; private String username;private transient String passwd;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPasswd() {return passwd;}public void setPasswd(String passwd) {this.passwd = passwd;}
}
結果:
read before Serializable: username: Alexia password: 123456read after Serializable: username: Alexia password: null?
總結
以上是生活随笔為你收集整理的Java transient关键字(序列化避免被反序列化获取敏感信息)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Supervisor进程守护监控
- 下一篇: Linux下的用户、组和权限的详细解释