我们在java反射实例化的一个类的实例的时候采用 Class.newInstance() 的时候,这个类必须包含一个无参的构造方法,这个在我们实现一些java的框架,比如 RPC 等功能的时候存在限制。
偶尔发现类一个这个项目,大体介绍如下:
项目地址:http://objenesis.org/
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:
Constructors that require arguments.
Constructors that have 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.
Needing to instantiate an object without calling the constructor is a fairly specialized task, however there are certain cases when this is useful:
Serialization, Remoting and Persistence - Objects need to be instantiated and restored to a specific state, without invoking code.
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();