我有一个简单的课程
public class Pet {
private String petName;
private int petAge;
public Pet() {
}
public Pet(String petName, int petAge) {
this.petName = petName;
this.petAge = petAge;
}
}
Run Code Online (Sandbox Code Playgroud)
当我试图找到参数时,我得到两个零.我仍然无法找出原因.有什么建议吗?
Constructor[] constructors = Pet.class.getDeclaredConstructors();
for (Constructor c : constructors) {
System.out.println(c.getTypeParameters().length);
}
Run Code Online (Sandbox Code Playgroud)
你使用的是错误的方法.
要获取每个构造函数的get参数数量,请使用:
System.out.println("ctor len " + c.getParameterCount());
Run Code Online (Sandbox Code Playgroud)
你会得到0和2,符合市场预期.
getTypeParameters().length 返回泛型类型参数的数量,并且没有任何构造函数具有泛型类型参数.
例如,如果您将第二个构造函数更改为:
public <Y> Pet(String petName, int petAge) {
....
}
Run Code Online (Sandbox Code Playgroud)
getTypeParameters().length将1为该构造函数.
查看Javadoc:
int java.lang.reflect.Constructor.getParameterCount()
返回此对象表示的可执行文件的形式参数的数量(无论是显式声明还是隐式声明,或两者都没有).
TypeVariable [] java.lang.reflect.Constructor.getTypeParameters()
返回TypeVariable对象的数组,这些对象表示由此GenericDeclaration对象以声明顺序表示的泛型声明声明的类型变量.如果底层泛型声明未声明类型变量,则返回长度为0的数组.
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |