I am currently learning about object serialization in Java and in my understanding it is even possible to serialize an object that implements the Serializable interface and pass it through a socket to a different program.
class Mammal implements Serializable
{
int legs = 4;
}
public class ObjectSerial
{
public static void main(String[] args)
{
try
{
FileOutputStream fo = new FileOutputStream("mammal.obj");
ObjectOutputStream oo = new ObjectOutputStream(fo);
Mammal m = new Mammal();
oo.writeObject(m);
oo.close();
}
catch(IOException e){}
//read object
try
{
FileInputStream fi = new FileInputStream("mammal.obj");
ObjectInputStream oo = new ObjectInputStream(fi);
Mammal m = (Mammal)oo.readObject();
System.out.println(m.legs);
}
catch(IOException e){}
catch(ClassNotFoundException cnf){}//this exception must also be caught
}
}
What puzzles me is when I want to retrieve the class members on the Server side for example, how would I ‘reach; the Serialized object.
try
{
FileInputStream fi = new FileInputStream("mammal.obj");
ObjectInputStream oo = new ObjectInputStream(fi);
Mammal m = (Mammal)oo.readObject();
System.out.println(m.legs);
}
catch(IOException e){}
catch(ClassNotFoundException cnf){}//t
In other words. In a different program the compiler will tell me that the symbol cannot be found.
Hope this question doesn’t sound very ignorant.
Just to confirm…how do i access the variables of the Serializedobject in a different program.
Regards
when you are de-serializing your “mammal.obj” on the server, you will need to have Mammal.class on the classpath. And also any objects Mammal depends on also on the classpath. That is the only way, and a downside of serialization. Its couples your client and server in a binary way.