Java反射getTypeParameters()。length返回0

时间:2017-06-11 05:58:28

标签: java reflection

我有一个简单的课程

public class Pet {
    private String petName;
    private int petAge;

    public Pet() {
    }

    public Pet(String petName, int petAge) {
        this.petName = petName;
        this.petAge = petAge;
    }
}

当我试图找到参数时,我得到两个零。我仍然无法找出原因。有什么建议吗?

        Constructor[] constructors = Pet.class.getDeclaredConstructors();
        for (Constructor c : constructors) {
            System.out.println(c.getTypeParameters().length);
        }

2 个答案:

答案 0 :(得分:6)

您使用的是错误的方法。

要获取每个构造函数的get参数数量,请使用:

System.out.println("ctor len " + c.getParameterCount());

您可以按预期获得02

getTypeParameters().length返回泛型类型参数的数量,并且没有任何构造函数具有泛型类型参数。

例如,如果您将第二个构造函数更改为:

public <Y> Pet(String petName, int petAge) {
    ....
}
对于该构造函数,

getTypeParameters().length将为1

参见Javadoc:

  

int java.lang.reflect.Constructor.getParameterCount()

     

返回此对象表示的可执行文件的形式参数(无论是显式声明还是隐式声明,或两者都没有)。

     

TypeVariable [] java.lang.reflect.Constructor.getTypeParameters()

     

返回TypeVariable对象的数组,这些对象表示由此GenericDeclaration对象以声明顺序表示的泛型声明声明的类型变量。如果底层泛型声明没有声明类型变量,则返回长度为0的数组。

答案 1 :(得分:0)

c.getParameterCount()

将根据您0的当前代码返回2non-typed constructor

相关问题