As we know Serialization
in java ,to quote from a blog here is used
to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running Java virtual machine.
- REST API CASE :
Now considering the second case , to send over a network to another running jvm , if we consider an example of a Rest API , i.e "host:port/path/resource".
Usually I use Spring's @RequestMapping
to return the resource model pojo class as ResponseEntity
. I do not implement Serializable
interface in the model class and all works fine , I get the response of the API in json.
ModelX.java
public class ModelX {
private int x = 2 ;
private String xs = "stringx";
// getters and setters
}
Controller method :
@RequestMapping(value = "/test",method=RequestMethod.POST)
public ResponseEntity<ModelX> getTestModel(@RequestBody ModelX mox){
ModelX mx = new ModelX();
mx.setX(mox.getX());
mx.setXs(mox.getXs());
return new ResponseEntity<ModelX>(mx, HttpStatus.OK) ;
}
Is it because Spring framework makes it Serializable under the hood with those RestAPI annotations ? If not , how without making it serializable we are able to send over a network .
- Persistence Case :
Just for more thought , Even in the case of persisting the Objects in database , we use @Entity
from JPA
, now I tested if the instance of any @Entity
annotated class IS-A
Serializable
or not . and it gives false.
@Entity
class Car {
int id ;
String name ;
//getters and setters
}
testMethod -
Car c = new Car();
System.out.println(c instanceof Serializable);
O/p - false
So even when we try to save this object's state in a database , ORM also does some kind of Serialization under the hood ?