gpt4 book ai didi

Java 反射 getTypeParameters().length 返回 0

转载 作者:行者123 更新时间:2023-11-29 06:52:09 25 4
gpt4 key购买 nike

我有一个简单的类

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);
}

最佳答案

你用错了方法。

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

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()

Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.

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

Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order. Returns an array of length 0 if the underlying generic declaration declares no type variables.

关于Java 反射 getTypeParameters().length 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44480833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com