When we use Class.newinstance () when Java reflects an instance of a class that is instantiated, This class must contain a parameterless constructor, which has limitations when we implement some Java frameworks, such as RPC.
The occasional discovery class one of this project, broadly described below:
Project Address: http://objenesis.org/
When would-want this?
Java already supports this dynamic instantiation of classes using Class.newInstance() . However, this is only works if the class have an appropriate constructor. There is many times when a class cannot is instantiated this and such as when the class contains:
-
constructors that require arguments.
-
Constructors that has side effects.
-
constructors that throw exceptions.
As a result, it is common to see restrictions in libraries stating that classes must require a default constructor. Objenesis aims to overcome these restrictions by bypassing the constructor on object instantiation.
Typical uses
Needing to instantiate an object without calling the constructor was a fairly specialized task, however there is certain C ASEs when this is useful:
-
serialization, Remoting and persistence -Objects need to BES instantiated and restored to a specific state, Witho UT invoking code.
-
Proxies, AOP Libraries and Mock Objects -Classes can is subclassed without needing to worry about the super () CO Nstructor.
-
Container Frameworks -Objects can be dynamically instantatiated in non-standard ways.
Use:
Maven dependencies:
<dependency> <groupId>org.objenesis</groupId> <artifactId>objenesis</artifactId> &L T;version>2.1</version></dependency>
Step by step
There is many different strategies that Objenesis uses for instantiating objects based on the JVM vendor, JVM version, Se Curitymanager and type of class being instantiated.
We have defined, different kinds of instantiation are required:
-
Stardard -No constructor'll be called
-
Serializable compliant -Acts like a object instantiated by Java standard Serialization. It means that the constructor of the first non-serializable the parent class would be called. However, Readresolve is isn't called and we never check if the object is serializable.
The simplest-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 has the objenesis implementation, you can then create an ObjectInstantiator , for a specific type.
Objectinstantiator thingyinstantiator = objenesis.getinstantiatorof (Mythingy.class);
Finally, you can use the instantiate new instances of this type.
Mythingy thingy1 = (mythingy) thingyinstantiator.newinstance (); Mythingy thingy2 = (mythingy) thingyinstantiator.newinstance (); Mythingy thingy3 = (mythingy) thingyinstantiator.newinstance ();
Java Instantiation Tool