java 静态变量如何被序列化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12775938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How come static variable is Serialized?
提问by Girish Nair
public class MySerializable implements Serializable{
private int x=10;
private static int y = 15;
public static void main(String...args){
AnotherClass a = new AnotherClass();
AnotherClass b;
//Serialize
try {
FileOutputStream fout = new FileOutputStream("MyFile.ser");
ObjectOutputStream Oout = new ObjectOutputStream(fout);
Oout.writeObject(a);
System.out.println( a.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//De-serialize
try {
FileInputStream fis = new FileInputStream("MyFile.ser");
ObjectInputStream Oin = new ObjectInputStream (fis);
b = (AnotherClass) Oin.readObject();
System.out.println( b.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
}
class AnotherClass implements Serializable{
transient int x = 8;
static int y = 9;
@Override
public String toString() {
return "x : " + x + ", y :" + y;
}
}
Can you please tell me how the static variable is serialized ??
你能告诉我静态变量是如何序列化的吗??
回答by Rohit Jain
Apparently, static variables can be serialized (But you should not do that), since serializationis the process of saving the stateof an instanceof a class, and static variables are common to all instances. They don't say anything about the instance's state, so, it wouldn't make sense at all.
显然,静态变量可以被串行化(但你不应该这样做),因为序列化是的过程中保存状态的的实例类的,和静态变量是共同的所有实例。他们没有说明实例的状态,因此,这完全没有意义。
Suppose you were allowed to serialize a static variable. Then, when you deserialize the instance, you will be getting an old copy of that variable, which might have been changed since then. Since the static variable is shared across all instances of the class, a change in the variable from any instance must be reflected in this instance.
假设您被允许序列化一个静态变量。然后,当您反序列化实例时,您将获得该变量的旧副本,此后该副本可能已更改。由于静态变量在类的所有实例之间共享,因此任何实例中变量的更改都必须反映在该实例中。
So, they should not be serialized, because the variable under these conditions could possibly violate its contract as a static variable.
因此,它们不应该被序列化,因为在这些条件下的变量可能会违反其作为静态变量的契约。
Serialization: -
序列化:-
- Should not serialize the static variables..
- 不应该序列化静态变量..
Deserialization: -
反序列化:-
- Instance will get the static fields that was loaded with the class.. So, any changes that might have been done for that variable will be liable for this instance also..
- Instance 将获得与类一起加载的静态字段.. 因此,可能对该变量所做的任何更改也将对该实例负责..
回答by NPKR
The Current output of MySerializable Class is below
MySerializable 类的当前输出如下
x : 8, y :9
x : 0, y :9
In this case the static variable are getting printed after calling toString() method, by this time it will reads value from class level variable.
在这种情况下,在调用toString() 方法后会打印静态变量,此时它将从类级别变量中读取值。
Try this:
试试这个:
Add this line of code in MySerializable Class after //Serialize
block
在 MySerializable Class//Serialize
块后添加这行代码
AnotherClass.y = 5;
the output is :
输出是:
x : 8, y :9
x : 0, y :5
this means the static variable is not storing in the file, it will read dynammically by toString() method.
这意味着静态变量没有存储在文件中,它将通过 toString() 方法动态读取。
回答by Theodore Murdock
Static variables cannot be and are not serialized.
静态变量不能也不会被序列化。
Your question seems to be based on the fact that you're seeing the same value from the static variable after serialization as before serialization, but this is not due to the value being serialized and restored.
您的问题似乎基于这样一个事实,即您在序列化后从静态变量中看到的值与序列化前相同,但这不是由于值被序列化和恢复所致。
This behavior is because the static initializer for that static variable sets it to 9, and it is never changed.
这种行为是因为该静态变量的静态初始值设定项将其设置为 9,并且永远不会更改。
To verify that static variables are not serialized, you can either perform NPKR's suggested change, modifying the static field between serialization and deserialization, or you could do the following:
要验证静态变量未序列化,您可以执行 NPKR 建议的更改,修改序列化和反序列化之间的静态字段,或者您可以执行以下操作:
Run this program, then comment out the bit that performs the serialization. You'll have the old serialized version on disk as a result.
运行这个程序,然后注释掉执行序列化的位。因此,您将在磁盘上拥有旧的序列化版本。
Then change the static initializer of the static field to y = 5
, and run the program again: you'll get 'x: 0 y: 5as the output, because the value
9` of the static field was not restored.
然后将静态字段的静态初始化器更改为y = 5
,再次运行程序:您将得到'x: 0 y: 5 as the output, because the value
9` 的静态字段未恢复。
回答by Jkcboys
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;
class TestJava implements Serializable{
public static int k = 10;
public int j=5;
public static void main(String[] args) {
TestJava tj1= new TestJava();
TestJava tj2;
try{ //serialization
FileOutputStream fos = new FileOutputStream("myclass.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tj1);
oos.close();
fos.close();
System.out.println("object serielized 1..."+tj1.j);
System.out.println("object serielized 2..."+tj1.k);
System.out.println("object serielized 3..."+k);
k=++k; // 'k' value incrementd after serialization
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
} catch(IOException ioex){
ioex.printStackTrace();
}
try{ //deserialization
FileInputStream fis = new FileInputStream("myclass.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
tj2 = (TestJava) ois.readObject();
ois.close();
fis.close();
System.out.println("object DEEEEserielized 1..."+tj2.j);
System.out.println("object DEEEEserielized 2..."+tj2.k);
System.out.println("object DEEEEserielized 3..."+k);
// in deserialization 'k' value is shown as incremented.
// That means Static varialbe 'K' is not serialized.
// if 'K' value is serialized then, it has to show old value before incrementd the 'K' value.
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
} catch(IOException ioex){
ioex.printStackTrace();
} catch(ClassNotFoundException CNFE){
CNFE.printStackTrace();
}
}
}
/* Output of the above program
object serielized 1...5
object serielized 2...10
object serielized 3...10
object DEEEEserielized 1...5
object DEEEEserielized 2...11
object DEEEEserielized 3...11
*/
回答by Kumar Vivek Mitra
-Serialization
is used to save the state of the objectduring serialization, so during the de-serialization the saved state can be used in order to resurrect an Identical object on the heap.
-Serialization
用于在序列化期间保存对象的状态,因此在反序列化期间,保存的状态可用于在堆上恢复相同的对象。
-Yesstatic
variable can be serialized
but it doesn't make any sense.....
-是的static
变量可以,serialized
但它没有任何意义.....