1 我在网上看了,说static变量不能序列化,但是我测试了一下,发现可以序列化,不知道是什么原因
2 看了一个兄弟的面试题,在网上没找到答案:java实现对象的序列化有哪两种方式?

解决方案 »

  1.   

    只有一种,实现serializable接口
      

  2.   

    static的变量是不可以被序列化的。
    除非你自己写readObject、writeObject方法。
    因为static变量是属于类的,
    如果你这个类的一个对象被序列化了,保存了static变量的值为A。
    可在因为这个类的另外一个对象变成了B,
    那就没什么意义了。
    如果是static final 应该也是可以的。不知道你怎么测试的,static变量可以被序列化。我知道除了实现serializable接口,还可以实现另外一个接口,
    不过那个接口也是实现了serializable接口的。
    我就不说了。
      

  3.   


    如果是static final的话,那就是常量了。序列化常量有意义吗?
    常量应该不能序列化,个人理解。
      

  4.   

    恩。
    说的对。
    static final确实没有必要序列化。
    做了个测试,也确实不行。
    还是得自己写writeObject才可以的。
      

  5.   

    呦~实现序列化通常用两个方法:一个是:实现Serializable接口,第二个就是实现Externalizable接口!
    不过后者是前者的子接口!
      

  6.   

    我在网上看的例子如下,从运行的程序看static变量可以序列化
    public class TestInherit{

        
    public static void main(String[] argc){

    try{
    MyClass object1=new MyClass("Hello",7,2.7e10);
    System.out.println("object1:"+object1);
    FileOutputStream fos=new FileOutputStream("serial");
    ObjectOutputStream oos=new ObjectOutputStream(fos);
    oos.writeObject(object1);
    oos.flush();
    oos.close();
    }
    catch(Exception e){
    System.out.println("Exception during serialization:"+e);
    System.exit(0);
    } //Object deserialization
    try{
    MyClass object2;
    FileInputStream fis=new FileInputStream("serial");
    ObjectInputStream ois=new ObjectInputStream(fis);
    object2=(MyClass)ois.readObject();
    ois.close();
    System.out.println("object2:"+object2);
    }
    catch(Exception e){
    System.out.println("Exception during deserialization:"+e);
    System.exit(0);
    }
    }
    }
    class MyClass implements Serializable{
    String s;
    static int  i;  //static变量
    double d;
    public MyClass(String s,int i,double d){
    this.s=s;
    this.i=i;
    this.d=d;
    }
    public String toString(){
    return "s="+s+";i="+i+";d="+d;
    }
    }
    ----------------------
    output:object1:s=Hello;i=7;d=2.7E10  序列化前
    object2:s=Hello;i=7;d=2.7E10  序列化后 i被序列化 没有抛出异常
      

  7.   


    就这段代码算怎么没验证?
    你先把object1序列化后,
    重新写一段代码执行,只是先声明一个MyClass的引用,改变static变量的值,
    然后反序列化object1,将引用的值付给 之前声明的那个MyClass的引用。
    你再输出下看看。
      

  8.   

    这个值是属于类MyClass的。
    之前你并没有把它序列化。
    反序列化自然也得不到它的值。
    之所以能输出,是因为它属于类,你加载了类MyClass,它就存在,且有值。