Hi,
If we construct a
String using a byte array and then do get Bytes on the string object, are we guarenteed to get the same byte array contents ?
I am getting them differently.
Due to my project requirements we need a converter for any generic object to String and String to Obejct, so we planned to use Serialization for that
I am pasting the
test code I am using and also the output. (SerialTestObject consists of one instance variable and getter method for that and implements Serializable interface)
public class SerialTest
{
public static void main(String args[]){
try{
// create two objects
SerialTestObject object1 = new SerialTestObject();
// serialize the first one
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object1);
oos.flush();
byte[] temp1 = baos.toByteArray();
for(int g=0; g < temp1.length; g++)
{
System.out.print(temp1[g]);
}
System.out.println();
String str = new String(temp1);
// read it back
byte[] temp2 = str.getBytes();
for(int g=0; g < temp2.length; g++)
{
System.out.print(temp2[g]);
}
ByteArrayInputStream bais = new ByteArrayInputStream(temp2);
ObjectInputStream ois = new ObjectInputStream(bais);
System.out.println(ois.readObject().getClass());
}
catch(Exception e){
e.printStackTrace();
}
}
Here is the output:
-84-1905115114016831011141059710884101115116799810610199116-115-4-116-5-
1264931-872017601115116018761069711897471089711010347831161141051101035912
01121160218410410511532105115329711032971161161141059811711610146
-84-190511511401683101114105971088410111511679981061019911663-4-116-5-1264
931-8720176011151160187610697118974710897110103478311611410511010359120112
1160218410410511532105115329711032971161161141059811711610146
java.io.InvalidClassException: SerialTestObject; local class incompatible: stream classdesc serialVersionUID = 4610715130369482665, local class serialVersionUID = -8215536608381689943
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:454)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1511)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1425)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1616)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1264)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:322)
at SerialTest.main(SerialTest.java:34)
B]If I use a static serialVersionUID the problem does not occur.[/B]
[added newlines for readability - Jim]
[ December 17, 2003: Message edited by: Jim Yingst ]