java 关键字: volatile、strictfp、transient

1. volatile


入门

(1). java中volatile关键字的含义

(2). 初学Java多线程:慎重使用volatile关键字


进阶

(1). Java 理论与实践: 正确使用 Volatile 变量

(2). 关于原子操作和volatile关键字~


扩展

 Java 原子操作


2. strictfp


Java中的strictfp关键字


3. transient


汉语翻译



在 java 里面该关键字可以用来使某个对象不具有持久性。


比如对象序列化中,为了保证安全性,我们可以在传递对象的过程中使某个数据如密码失去持久化的作用。


下面举例说明


package it.mark;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	private static final String FILE_NAME = "user.info";

	private Date date = new Date();
	private String userName;
	private/* transient */String pwd;

	public User(String user, String password) {
		userName = user;
		pwd = password;
	}

	@Override
	public String toString() {

		return "user info: \n   " + "user: " + userName + "\n   date : "
				+ date.toString() + "\n   password: " + pwd;
	}

	public static void main(String[] args) {
		User user = new User("mark", "123456");
		
		printMsg("write info: " + user.toString());

		printMsg("*********************************************************");

		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
					FILE_NAME));
			out.writeObject(user);
			out.close();

			ObjectInputStream in = new ObjectInputStream(new FileInputStream(
					FILE_NAME));
			User readUser = (User) in.readObject();

			printMsg("read info: " + readUser.toString());

			in.close();
		} catch (Exception e) {
			printMsg(e.getMessage());
		}
	}

	private static void printMsg(String msg) {
		System.out.println(msg);
	}
}


运行上面代码,可以看出,在read之后,还是可以看到 password 的




修改

private/* transient */String pwd;

private transient String pwd;




获取的 password 是 null






©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页