其实在反射中我们使用到Constructor的时候不是太多,因为如果我们有无参构造函数,一般使用有参够构造函数的很少,除非是在初始化的时候,但是初始化的时候也是直接使用空的构造函数然后使用相应的get和set方法来设置相应的值,这里就来说几种获取构造函数的方式以及几个方法,仅供参考:
getConstructor(Class<?>...ParametersType):根据传入的参数顺序获取属性为public的构造器,没有则抛出NoSuchMethodException
getConstructors():获取所有的类型为public的构造器,返回的是数组,没有则NoSuchMethodException
getDeclaredConstructor(Class<?>...ParametersType):根据传入的参数列表获取类型为public或者protected或者private构造器,没有则NoSuchMethodException
getDeclaredConstructors():获取类型为public或者protected或者private构造器,返回的是数组,没有则NoSuchMethodException
也可以根据返回的constructor获取部分有关constructor的属性:
getName():返回的是constructor的名字
getParameterCount():返回此构造函数参数的个数
getGenericParameterTypes():获取参数的类型
getDeclaringClass():获取constructor所属的类