Ja, Sie können, aber Sie müssen deklarieren, dass Ihre Klasse die java.io.Serializable-Schnittstelle implementiert. Hier
ist ein komplettes Beispiel in einer Datei 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();
}
}
}
Ergebnisse: Pojo mit 1 Feldgrße = 34
Pojo mit 2 Feldern size = 42
Pojo mit 3 Feldern Größe = 50
Pojo ohne Felder = 25
Pojo ohne Felder und ein Verfahren, das eine int size zurück = 26
ja, in Ihrem Fall nicht. – SomeJavaGuy
Wie planen Sie, es zu serialisieren? ObjectOutputStream? Dann muss Ihre Klasse "Serializable" implementieren. Wenn ja: Warum versuchst du es nicht und schaust dir die Anzahl der Bytes an? – f1sh
Was ist passiert, als du es versucht hast? – Jesper