java 实例化工具

咱们在java反射实例化的一个类的实例的时候采用 Class.newInstance() 的时候,这个类必须包含一个无参的构造方法,这个在咱们实现一些java的框架,好比 RPC 等功能的时候存在限制。
html


偶尔发现类一个这个项目,大致介绍以下:java

项目地址:http://objenesis.org/ api


When would you want this?

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

Typical uses

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>

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, 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();
相关文章
相关标签/搜索