Is it possible in java to create 'blank' instance of class without no-arg constructor using reflection?

Vladimir picture Vladimir · Nov 9, 2010 · Viewed 16.5k times · Source

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.

Answer

Brad Cupit picture Brad Cupit · Nov 9, 2010

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).