小编典典
public static int sizeof(Object obj) throws IOException {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
return byteOutputStream.toByteArray().length;
}
我只是测试了一下。您要计算Serializable其大小的对象需要实现(这意味着您可能仅为了获得其大小就必须标记每个对象。这可能是不希望的)。我写了一个快速而肮脏的程序来测试一下:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Sizeof {
public static class Person implements Serializable {
private String name;
private String age;
public Person(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
public static void main(String[] args) {
Person p1 = new Person("Alby", "20");
Person p2 = new Person("VeryLongName", "100");
String s1 = "This is it";
String s2 = "This";
try {
System.out.println("p1 " + sizeof(p1));
System.out.println("p2 " + sizeof(p2));
System.out.println("s1 " + sizeof(s1));
System.out.println("s2 " + sizeof(s2));
}
catch(Exception e) {
e.printStackTrace();
}
}
public static int sizeof(Object obj) throws IOException {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
return byteOutputStream.toByteArray().length;
}
}
这给了我:
p1 85
p2 94
s1 17
s2 11
编辑
Stephen C的答案突出了此方法的一些注意事项。
2020-12-03