There are two main interfaces in Objenesis:
interface ObjectInstantiator { Object newInstance(); }
interface InstantiatorStrategy { ObjectInstantiator newInstantiatorOf(Class type); }
Note: All Objenesis classes are in the
org.objenesis
package.
There are many different strategies that Objenesis uses for instantiating objects based on the JVM vendor, JVM version, SecurityManager and type of class being instantiated.
We have defined that two different kinds of instantiation are required:
The simplest way to use Objenesis is by using ObjenesisStd (Standard) and ObjenesisSerializer (Serializable compliant). By default, automatically determines the best strategy - so you don't have to.
Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer
Once you have the Objenesis implementation, you can then create an ObjectInstantiator
, for a specific type.
ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(MyThingy.class);
Finally, you can use this to instantiate new instances of this type.
MyThingy thingy1 = (MyThingy)thingyInstantiator.newInstance(); MyThingy thingy2 = (MyThingy)thingyInstantiator.newInstance(); MyThingy thingy3 = (MyThingy)thingyInstantiator.newInstance();
To improve performance, it is best to reuse the ObjectInstantiator
objects as much as possible. For example, if you are instantiating multiple instances of a specific class,
do it from the same ObjectInstantiator
.
Both InstantiatorStrategy
and ObjectInstantiator
can be shared between multiple
threads and used concurrently. They are thread safe.
(For the impatient)
Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer MyThingy thingy1 = (MyThingy) objenesis.newInstance(MyThingy.class); // or (a little bit more efficient if you need to create many objects) Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(MyThingy.class); MyThingy thingy2 = (MyThingy)thingyInstantiator.newInstance(); MyThingy thingy3 = (MyThingy)thingyInstantiator.newInstance(); MyThingy thingy4 = (MyThingy)thingyInstantiator.newInstance();