Java Reflection getConstructor方法 [英] Java Reflection getConstructor method
问题描述
假设我有类 A
和 B
,其中 B
extends A
。我还在 B
中有一个构造函数,其中一个参数类型为 A
。我还有一个 B
类型的对象,名为 bObj
。
Lets say I have classes A
and B
, where B
extends A
. I also have a constructor in B
with one argument which is of type A
. I also have an object of type B
called bObj
.
有没有办法调用 B.class.getConstructor(new Class [] {bObj.getClass()})
并获取构造函数,因为 B
扩展 A
?目前我得到一个 NoSuchMethodException
。
Is there a way to call B.class.getConstructor(new Class[] { bObj.getClass() })
and get the constructor since B
extends A
? At the moment I'm getting a NoSuchMethodException
.
问候,
Stan
Regards, Stan
推荐答案
我建议你看一下 ConstructorUtils
.apache.org / lang /rel =noreferrer> Apache Commons Lang 。
他们拥有构造函数发现方法的所有方式。
I suggest you have a look at the ConstructorUtils
from Apache Commons Lang.
They have all manners of constructor discovery methods.
您的案例应该包含在匹配可访问构造函数。
这里是一个我的例子在上下文中使用。
基本上,你这样称呼:
Here is an example of the method used in context. Basically, you call it like this:
private <T> T instantiate(Class<?> input, Object parameter) {
try {
Constructor<?> constructor = ConstructorUtils.getMatchingAccessibleConstructor(input, parameter.getClass());
return (T) constructor.newInstance(parameter);
} catch (Exception e) {
//handle various exceptions
}
}
这篇关于Java Reflection getConstructor方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!