sgarg
sgarg

Reputation: 2459

Deserialize object without knowing its type in Java

Normally the deserialization is done in the following way:

PersistentTime time = null;
time = (PersistentTime)ois.readObject();

where ois is ObjectInputStream object and PersistentTime is the class we want to deserialize to.

So if my application has 2 or 3 kinds of objects being sent over the network, is it possible to deserialize the object without knowing the type or know the type of object first and deserialize later according to that type?

Upvotes: 1

Views: 3456

Answers (3)

AlexR
AlexR

Reputation: 115328

You can first read the object, then check its type, then cast to appropriate type and use, e.g.

Object obj = ois.readObject();

if (obj instanceof PersistentTime) {
    PersistentTime time =- (PersistentTime)obj;
    // use time
}

Upvotes: 1

miaout17
miaout17

Reputation: 4875

Deserialize it then check its type

Object object = ois.readObject();
if (object instanceof PersistentTime) {
    PersistentTime time = (PersistentTime)object;
    // Do something to PersistentTime
} else if (object instanceof SomeClass) {
    // Do something to someclass
}

Upvotes: 3

Thomas
Thomas

Reputation: 181745

Of course; you're doing that already! But if you want to save the typecast for later:

Object deserialized = ois.readObject();

if (deserialized instanceof PersistentTime) {
  PersistentTime time = (PersistentTime)deserialized;
  // do something with time...
} else if (deserialized instanceof SomethingElse) {
  ...
} else if (...) {
  ...
}

Upvotes: 8

Related Questions