Java - 在不知道构造函数参数的情况下使用反射创建新实例 [英] Java - Create new Instance using Reflection without knowing constructor params

查看:51
本文介绍了Java - 在不知道构造函数参数的情况下使用反射创建新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建许多类的新实例.我正在使用反射,但是当我创建 c.newInstance() 时,没有空参数构造函数"的类会抛出 java.lang.InstantiationException.

I need to create new instances of many classes. I'm using reflection but when I make c.newInstance(), the classes without 'empty parameter constructor' throws an java.lang.InstantiationException.

现在,我该如何创建每个类的实例?

Now, how can i do to create instances of every classes ?

我知道我可以使用 c.getConstructor(Class).newinstance(params) 创建没有空参数构造函数"的类的实例,但我不知道每个类的参数.

I know that i can use c.getConstructor(Class).newinstance(params) to create instances of classes that doesn't have 'empty parameter constructor', but i do not know the params of each classes.

还有一件事,所有这些类都是从另一个名为 ParentClass 的类扩展而来的,所以我可以使用的一种解决方法是在 ParentClass 中包含一些代码,强制子类实现空参数构造函数",但不要知道如何做到这一点.

One more thing, all those classes extend from another class called ParentClass, so one workaround that i could use is to include some code in the ParentClass that force the child classes to implement an 'empty parameter constructor', but don't know how to do this.

提前致谢!

推荐答案

您可以调用 Class.getConstructors() 获取给定类的所有构造函数.

You can call Class.getConstructors() to get all the constructors for a given class.

在每个构造函数上,您可以调用Constructor.getGenericParameterTypes() 以了解哪个它期望的参数.

On each Constructor, you can call Constructor.getGenericParameterTypes() to learn which parameters it expects.

这篇关于Java - 在不知道构造函数参数的情况下使用反射创建新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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