Java序列化的时候两种成员变量不能被序列化 一种是static 的还有一种是 transient的。
但是当笔者写了一个demo的时候,发现,"静态的成员变量居然可以拿到"。
demo的代码如下
package com.java;
import java.io.*;
/**
* Created by HuLuo on 2016/8/15.
*/
public class Hello
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
User user = new User();
FileOutputStream fileOutputStream = new FileOutputStream( "helloworld.txt" );
ObjectOutputStream objectOutputStream = new ObjectOutputStream( fileOutputStream );
objectOutputStream.writeObject( user );
FileInputStream fileInputStream = new FileInputStream( "helloworld.txt" );
ObjectInputStream objectInputStream = new ObjectInputStream( fileInputStream );
User user1 = (User) objectInputStream.readObject();
System.out.println(user1);
}
}
class User implements Serializable
{
String name;
static String password;
transient int age;
public User()
{
this.name = "张三";
this.password = "密码";
this.age = 23;
}
@Override
public String toString()
{
return name + "+++++" + password + "+++++" + age;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
out.defaultWriteObject();
}
}
其实static的静态成员变量是不能被序列化这个观点是正确的,
造成可以拿到static序列化之后的假象是因为static 属于类的,得到的是JVM已经加载好的Class的static变量的值,
当你重开一个进程或者在另一个机器上反序列化的时候,就得不到static的值了
将我上面的代码如下的部分注释掉,重新运行即可得到验证。
// User user = new User();
//
// FileOutputStream fileOutputStream = new FileOutputStream( "helloworld.txt" );
//
// ObjectOutputStream objectOutputStream = new ObjectOutputStream( fileOutputStream );
//
// objectOutputStream.writeObject( user );