Reputation: 477
I have a simple class
public class Pet {
private String petName;
private int petAge;
public Pet() {
}
public Pet(String petName, int petAge) {
this.petName = petName;
this.petAge = petAge;
}
}
When I'm trying to find arguments, I get two zeros. I still can't find out why. Any suggestion?
Constructor[] constructors = Pet.class.getDeclaredConstructors();
for (Constructor c : constructors) {
System.out.println(c.getTypeParameters().length);
}
Upvotes: 1
Views: 400
Reputation: 4207
c.getParameterCount()
will return 0
and 2
as per your current code for non-typed constructor
.
Upvotes: 0
Reputation: 393781
You are using the wrong method.
To the get number of arguments of each constructor, use:
System.out.println("ctor len " + c.getParameterCount());
You'll get 0
and 2
, as expected.
getTypeParameters().length
returns the number of generic type parameters, and none of your constructors have generic type parameters.
If, for example, you change your second constructor to:
public <Y> Pet(String petName, int petAge) {
....
}
getTypeParameters().length
will be 1
for that constructor.
See the 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.
Upvotes: 6