[英]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: 我得到它使用反射,我想检查参数的类型,确保它是否是一种java.util.Date,我这样做:
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 如果您想知道某个方法是否具有Date
类型的单个参数,则可以执行此操作
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
. 因为那时你会发现该方法是否有一个接受Date
参数。 For example, the parameter could be of type Object
, Cloneable
or Comparable<?>
and you could still pass a Date
. 例如,参数可以是Object
, Cloneable
或Comparable<?>
,您仍然可以传递Date
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.