简体   繁体   中英

How to check the type of method parameter when use reflection in java

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM