As we know we can instantiate an object without new
keyword by using classloader/object cloning/object serialization. When I am using these techniques to create an object, is the constructor called or not?
views:
120answers:
2
+1
A:
As far as I know all the three use the constructor even serialization.
http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html
The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case
Xavier Combelle
2010-07-02 08:47:39
Where does that quote come from? You should (ideally) provide a link or else supply a citation.
APC
2010-07-02 08:52:18
post edited to add link
Xavier Combelle
2010-07-02 09:26:02
I think this citation only applies to subclasses of non-serializable classes. In that case the super-class has to declare a no-argument constructor. The fields of the serializable class itself are initialised without calling the constructor.
Jörn Horstmann
2010-07-02 09:43:47
@Jörn I think you are right
Xavier Combelle
2010-07-02 14:03:13
+3
A:
For Object.clone
no constructor is called.
For serialisation, the most derived non-serialisable base-class no-arg constructor is called. Typically implemented by loading bytecode that does not validate. The constructor must be accessible to the base-most serialisable class.
Tom Hawtin - tackline
2010-07-02 10:32:40