Create instance without invoking constructor

It is not always true that constructors will be invoked when constructing an object. I actually stumbled today wondering why the no argument constructor was not invoked when deserializing object from XML using Java XStream library, and after doing some search found that there are ways to create object without calling the constructor. I wouldn’t say this is a good practice especially when we are not writing library code, but just a reminder that some code may work like this, so when dealing with object deserialization, we need to be very careful on checking whether our fields are initialized.

The following article explains the situation in Java, where binary deserializing an object won’t invoke the constructor if the object’s class implements Serializable.
http://www.javaspecialists.eu/archive/Issue175.html
While the other way of creating an instance skipping calling constructor mentioned in this article by using sun.reflect.ReflectionFactory no longer works in post Java 1.7 as ReflectionFactory class is removed.

C# also has several cases where the instance is created without invoking any constructor.

  • FormatterServices.GetUninitializedObject
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    public class Person
    {
        public int Number = 42;

        public string Name { get; set; }

        public Person()
        {
            Name = "Univer";
        }

        static void Main(string[] args)
        {
            var person = (Person)FormatterServices.GetUninitializedObject(typeof(Person));
            Console.WriteLine(person.Name ?? "[null]");
            Console.WriteLine(person.Number);
        }
    }
}

Which gives the following output:

[null]
0
  • Object.MemberwiseClone
namespace Demo
{
    public class Person
    {
        public Person()
        {
            Console.WriteLine("Constructor called");
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Creating person instance");
            var person = new Person();
            Console.WriteLine("Person instance created");

            Console.WriteLine();

            Console.WriteLine("Cloning person instance");
            var cloned = (Person)person.MemberwiseClone();
            Console.WriteLine("Person instance cloned");
        }
    }
}

Which gives the following output:

Creating person instance
Constructor called
Person instance created

Cloning person instance
Person instance cloned

Leave a Reply

Your email address will not be published. Required fields are marked *