Objenesis is a neat little library for instantiating classes . Consider the following class:
If the structure of the class and its constructor is known, then a framework can instantiate this class purely using reflection:
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:
Objenesis provides the solution here, of being able to instantiate an instance of Person class without needing to call its constructor:
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");
Exception:
java.lang.NoSuchMethodException: mvcsample.obj.Person.<init>()
at java.lang.Class.getConstructor0(Class.java:2810)
at java.lang.Class.getDeclaredConstructor(Class.java:2053)
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();