咱們在java反射實例化的一個類的實例的時候採用 Class.newInstance() 的時候,這個類必須包含一個無參的構造方法,這個在咱們實現一些java的框架,好比 RPC 等功能的時候存在限制。
html
偶爾發現類一個這個項目,大致介紹以下:java
項目地址:http://objenesis.org/ api
Java already supports this dynamic instantiation of classes using Class.newInstance()
. However, this only works if the class has an appropriate constructor. There are many times when a class cannot be instantiated this way, such as when the class contains:app
Constructors that require arguments.框架
Constructors that have side effects.maven
Constructors that throw exceptions.ide
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.ui
Needing to instantiate an object without calling the constructor is a fairly specialized task, however there are certain cases when this is useful:this
Serialization, Remoting and Persistence - Objects need to be instantiated and restored to a specific state, without invoking code.spa
Proxies, AOP Libraries and Mock Objects - Classes can be subclassed without needing to worry about the super() constructor.
Container Frameworks - Objects can be dynamically instantatiated in non-standard ways.
使用:
maven 依賴:
<dependency> <groupId>org.objenesis</groupId> <artifactId>objenesis</artifactId> <version>2.1</version> </dependency>
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, readResolve is 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();