user1473452
user1473452

Reputation: 13

How to turn a java.lang.Object into another type of object?

I can make my program write a .dat file with an array of Node (an object that contains registry information:name,telephone numbers,...) using ObjectOutputStream, but I am having problems reading this same file, since the file contains an object that is different from the Node[] I used earlier.

My problems will be solved if I can make one of them:

I don't known the official name for this, so I am having problems finding an answer.

Upvotes: 1

Views: 253

Answers (1)

Thilo
Thilo

Reputation: 262474

The Object returned from the ObjectInputStream will have the same type it had when you wrote it to the file in the first place.

You will have to cast it at runtime, though, because the compiler cannot know what type that will be.

 Object obj = stream.readObject();
 Node[] nodes = (Node[]) obj;

If your format is flexible, so that you do not know what exactly to expect, you can use instanceof to check the various possibilities first.

 if (obj instanceof Node[]){
     // do something
 }
 else if (obj instanceof String) { 
     // do something
 }
 else {
    throw new IOException("unexpected object in data stream "+ obj);
 }

Upvotes: 3

Related Questions