Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, convert(cast) Serializable objects to other objects

I'm using Session.save() method (in Hibernate) to persist my entity objects which returns an object of type java.io.Serializable.

The returned value is the generated primary key for the entity.

The generated primary key is of type long (or bigint).

The question is that: How can I convert or cast the returned value to long?

Serializable result = session.save(myEntityObject);

//This line of code fails. 
long r = (long)result;
like image 871
Ali Khoshsirat Avatar asked Sep 29 '11 14:09

Ali Khoshsirat


People also ask

Can a serialized object be transferred over a network?

Using serialization, an object can be transferred across domains through firewalls, as well as be used for different languages and platforms. The formats of serialized objects are standardized so as to be able to be read by different platforms, if needed.

When an object is serialized it is converted into what?

Data serialization is the process of converting an object into a stream of bytes to more easily save or transmit it. The reverse process—constructing a data structure or object from a series of bytes—is deserialization.

Can we transfer object without serialization?

You don't always require serialization/deserialization. If you're sending an object over a network, then it gets serialized to send it via a byte stream. That's the point of serialization, precisely so that you CAN send via a network.

Can we serialize class without implementing serializable interface?

If the superclass is Serializable, then by default, every subclass is serializable. Hence, even though subclass doesn't implement Serializable interface( and if its superclass implements Serializable), then we can serialize subclass object.


3 Answers

Try casting the result (since it's not a primitive) to Long instead of long.

Long r = (Long)result;
long longValue = r.longValue();
like image 100
Bhesh Gurung Avatar answered Sep 23 '22 15:09

Bhesh Gurung


Try

long r = Long.valueOf(String.valueOf(result)).longValue();
like image 40
James DW Avatar answered Sep 24 '22 15:09

James DW


Have you tried using a debugger and breaking at that line to see what "result" is exactly?

It could be BigDecimal or Long or ...

Alternatively, cant you just call the primary key getter method on the object - I'd have hoped it would be set by that point.

HTH, Chris

like image 25
Chris Kimpton Avatar answered Sep 25 '22 15:09

Chris Kimpton