Reputation: 1346
I have a method like that:
public void get(Date date)
And I get it use reflection, and I want to check the type of parameter, make sure whether it is a type of java.util.Date, I do it like that:
Class<?> parametersType = method.getParameterTypes();
// check it
if (parametersType[].equals(java.util.Date.class))
{
// do something
}
I want to know, are there any other way?
Upvotes: 1
Views: 1152
Reputation: 37645
If you want to know if a method has a single parameter of type Date
you can do
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length == 1 && parameters[0] == Date.class)) {
// do something
}
If might however be better to do
if (parameters.length == 1 && parameters[0].isAssignableFrom(Date.class))
because then you will find out if the method has a single parameter that will accept a Date
. For example, the parameter could be of type Object
, Cloneable
or Comparable<?>
and you could still pass a Date
.
Upvotes: 3