我们可以在没有任何理智的情况下序列化一个班级

时间:2016-11-25 11:00:05

标签: java serialization

我们可以在没有任何成员的情况下序列化一个类吗?我的课程如下

Class test
{
  public void method1(){ 
    //No code
  }
  public void method2(){
    //No code 
  }
}

如果是,那么selialized目标文件的大小是多少?

2 个答案:

答案 0 :(得分:1)

当然可以。但是你需要写

Class test implements java.io.Serializable

启动Java的(相当聪明的)序列化机制,实际上你应该在类中提供serialVersionUID值作为静态字段:

static final long serialVersionUID = 1L;

避免依赖Java编译器生成器(可能与编译器实现不同)。

答案 1 :(得分:1)

是的,你可以,但你必须声明你的类实现了java.io.Serializable接口。

以下是一个文件 Main.java

中的完整示例
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import static java.lang.System.*;

class ObjectSize {

    public static byte[] toByteArray(Object object) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(bos);
        out.writeObject(object);
        return bos.toByteArray();
      } 


    public static int getSize(Object obj) throws IOException{

        return toByteArray(obj).length;

    }

}


class Pojo1 implements Serializable{

    private static final long serialVersionUID = 1L;
    private int x = 0 ;
}

class Pojo2 implements Serializable{

    private static final long serialVersionUID = 1L;
    private int x, y = 0 ;
}

class Pojo3 implements Serializable{

    private static final long serialVersionUID = 1L;
    private int x, y , z = 0 ;
}

class Test implements Serializable
{

    private static final long serialVersionUID = 1L;
    public void method1(){}
    public void method2(){}
}


class Test2 implements Serializable
{

    private static final long serialVersionUID = 1L;
    public void method1(){}
    public void method2(){}
    public void method3(){}
    public int method4(){return 100;}
    public int method5(){return 0;}
}


public class Main {

    public static void main(String [] args) {

        try {

            out.println("Pojo with 1  field  size = "+ObjectSize.getSize(new Pojo1()));
            out.println("Pojo with 2  fields size = "+ObjectSize.getSize(new Pojo2()));
            out.println("Pojo with 3  fields size = "+ObjectSize.getSize(new Pojo3()));
            out.println("Pojo with no fields = "+ObjectSize.getSize(new Test()));
            out.println("Pojo with no fields and a method which returns an int size = "+ObjectSize.getSize(new Test2()));


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

结果 Pojo,1场大小= 34

Pojo,2个字段大小= 42

Pojo,3个字段大小= 50

没有字段的Pojo = 25

没有字段的Pojo和返回int size = 26

的方法