是否可以在java中使用反射创建没有无参数构造函数的类的“空白"实例? [英] Is it possible in java to create 'blank' instance of class without no-arg constructor using reflection?

查看:124
本文介绍了是否可以在java中使用反射创建没有无参数构造函数的类的“空白"实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有默认构造函数的类.我需要一种方法来获取此类的空白"实例.'blank' 表示实例化后所有类字段都应具有默认值如空、0 等.

I have a class which has not default constructor. And I need a way to get 'blank' instance of this class. 'blank' means that after instantiation all class fields should has default values like null, 0 etc.

我问是因为我需要能够序列化/反序列化对象的大树.而且我无法访问此对象类的源,并且类既没有默认构造函数也没有实现可序列化.尝试序列化此类结构可能不是一个好主意,但替代方案是将其转换为更易于序列化的内容.

I'm asking because I need to be able serialize/desirialize big tree of objects. And I have no access to sources of this objects classes and classes has neither default constructors nor implements serializable. It is likely not very good idea to try to serialize such structure but the alternative is to convert it to something more easily serializable.

推荐答案

使用标准反射,没有,但有一个库可以为您完成:客观性.

With standard reflection, no, but there is a library that can do it for you: objenesis.

它专门设计用于在没有默认构造函数的情况下实例化类,并且它被其他序列化库使用,例如 xstream.

It's specifically designed to instantiate classes without default constructors, and it's used by other serialization libraries like xstream.

注意:在这些情况下可能不会调用构造函数(但这可能是您想要的).

Note: the constructor might not be called in these cases (but that's presumably what you want).

这篇关于是否可以在java中使用反射创建没有无参数构造函数的类的“空白"实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆