Twenty Second Tutorial
There are two main interfaces in Objenesis:
- ObjectInstantiator
- Instantiates multiple instances of a single class.
interface ObjectInstantiator { Object newInstance(); }
- InstantiatorStrategy
- A particular strategy for how to instantiate a class (as this differs for different types of classes).
interface InstantiatorStrategy { ObjectInstantiator newInstantiatorOf(Class type); }
Note: All Objenesis classes are in the
org.objenesis
package.
Step By Step
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:
- Stardard - No constructor will be called
- Serializable compliant - Acts like an object instantiated by java standard
serialization. It means that the constructor of the first non-serializable parent class will
be called. However, specific implementation methods (e.g.
readResolve()
) are not called and we never check if the object is serializable.
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();
Performance and Threading
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.
That Code Again
(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();