您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

静态变量为什么不能序列化

2024/5/5 20:27:35发布49次查看
静态成员属于类级别的,所以不能序列化,这里的不能序列化的意思,是序列化信息中不包含这个静态成员域
这里有一个示例很好的证明了静态变量为什么不能序列化:
类student1
package test; import java.io.serializable; public class student1 implements serializable{ private static final long serialversionuid = 1l; private string name; private transient string password; private static int count = 0; public student1(string name,string password){ system.out.println("调用student的带参构造方法 "); this.name = name; this.password = password; count++; } public string tostring(){ return "人数:" + count + "姓名:" + name + "密码:" + password; }}
类objectsertest1
package test; import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.ioexception;import java.io.objectinputstream;import java.io.objectoutputstream; public class objectsertest1 { public static void main(string args[]){ try{ fileoutputstream fos = new fileoutputstream("test.obj"); objectoutputstream oos = new objectoutputstream(fos); student1 s1 = new student1("张三","123456"); student1 s2 = new student1("王五","56"); oos.writeobject(s1); oos.writeobject(s2); oos.close(); fileinputstream fis = new fileinputstream("test.obj"); objectinputstream ois = new objectinputstream(fis); student1 s3 = (student1) ois.readobject(); student1 s4 = (student1) ois.readobject(); system.out.println(s3); system.out.println(s4); ois.close(); } catch (ioexception e) { e.printstacktrace(); } catch (classnotfoundexception e1) { e1.printstacktrace(); } }}
运行结果:
调用student的带参构造方法
调用student的带参构造方法
人数:2姓名:张三密码:null
人数:2姓名:王五密码:null
类test1
package test; import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.ioexception;import java.io.objectinputstream;import java.io.objectoutputstream; public class test1{ public static void main(string args[]){ try { fileinputstream fis = new fileinputstream("test.obj"); objectinputstream ois = new objectinputstream(fis); student1 s3 = (student1) ois.readobject(); student1 s4 = (student1) ois.readobject(); system.out.println(s3); system.out.println(s4); ois.close(); } catch (ioexception e) { e.printstacktrace(); } catch (classnotfoundexception e1) { e1.printstacktrace(); } } }
运行结果:
人数:0姓名:张三密码:null
人数:0姓名:王五密码:null
总结:
类objectsertest1 的运行结果显示count=2,似乎被序列化了,但是类test1的运行结果显示count=0并未被序列化。
”序列化保存的是对象的状态,静态变量数以类的状态,因此序列化并不保存静态变量。
这里的不能序列化的意思,是序列化信息中不包含这个静态成员域
objectsertest1 测试成功,是因为都在同一个机器(而且是同一个进程),因为这个jvm已经把count加载进来了,所以你获取的是加载好的count,如果你是传到另一台机器或者你关掉程序重写写个程序读入test.obj,此时因为别的机器或新的进程是重新加载count的,所以count信息就是初始时的信息。“-----来自参考网页
重写类test1读取test.obj显示的结果是count的初始时的信息,也验证了上面一段话。
最后,java对象的static,transient 修饰的属性不能被序列化。
以上就是静态变量为什么不能序列化的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product