Wednesday, January 1, 2014

Objenesis for class instantiation

Objenesis is a neat little library for instantiating classes . Consider the following class:

public class Person {
    private final String firstName;
    private final String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

If the structure of the class and its constructor is known, then a framework can instantiate this class purely using reflection:

Constructor<Person> ctor = Person.class.getDeclaredConstructor(String.class, String.class);
Person personThroughCtor = ctor.newInstance("FirstName", "LastName");

However, if the constructor structure is not known ahead of time, creating the class instance is not easy, for eg the following will throw an exception:

Constructor<Person> ctor = Person.class.getDeclaredConstructor();
Person personThroughCtor = ctor.newInstance("FirstName", "LastName");


java.lang.NoSuchMethodException: mvcsample.obj.Person.<init>()
 at java.lang.Class.getConstructor0(
 at java.lang.Class.getDeclaredConstructor(

Objenesis provides the solution here, of being able to instantiate an instance of Person class without needing to call its constructor:

Objenesis objenesis = new ObjenesisStd(true);
ObjectInstantiator personInstantiator = objenesis.getInstantiatorOf(Person.class);

Person person = (Person)personInstantiator.newInstance();

No comments:

Post a Comment