I have a class which has not default constructor. And I need a way to get 'blank' instance of this class. 'blank' means that after instantiation all class fields should has default values like null, 0 etc.
I'm asking because I need to be able serialize/desirialize big tree of objects. And I have no access to sources of this objects classes and classes has neither default constructors nor implements serializable. It is likely not very good idea to try to serialize such structure but the alternative is to convert it to something more easily serializable.
With serialization, you create a new object by deserializing the whole object state from an input stream. No constructor is invoked in this case. With JNI, there is the AllocObject function, which allocates the space for a new object, also without calling a constructor.
Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.
newInstance() method, which requires a no-argument constructor to create an instance. It's effectively equivalent to the new Entity(). This method throws InstantiationException if it doesn't found any no-argument constructor in the Entity class, and that's why it's advised to provide a no-argument constructor.
Actually, yes, it is possible to bypass the constructor when you instantiate an object, if you use objenesis to instantiate the object for you. It does bytecode manipulations to achieve this. Deserializing an object will also bypass the constructor. It isn't possible to do this using reflection.
With standard reflection, no, but there is a library that can do it for you: objenesis.
It's specifically designed to instantiate classes without default constructors, and it's used by other serialization libraries like xstream.
Note: the constructor might not be called in these cases (but that's presumably what you want).
Having Class instance provided as variable clazz:
ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); Constructor objDef = parent.getDeclaredConstructor(); Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef); clazz.cast(intConstr.newInstance());
as described in http://www.javaspecialists.eu/archive/Issue175.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With