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

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

问题描述

我有一个没有默认构造函数的类。我需要一种方法来获得这个类的空白实例。 'blank'意味着在实例化之后,所有类字段应该具有默认值
,例如null,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.

我问的是因为我需要能够序列化/ desirialize大树的对象。我没有访问这个对象的类的源和类没有默认构造函数也不实现serializable。这可能不是一个好主意,尝试序列化这样的结构,但替代方法是将其转换为更容易序列化的东西。

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.

推荐答案

使用标准反射,没有,但有一个图书馆可以为你做: objenesis

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中创建'空白'实例的类,没有没有arg的构造函数使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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