[英]Checking the class of a Java Reflection Type
我一直在寻找在SO上看到的答案,到目前为止,我找不到适合我的任何解决方案。 本质上,我只是使用反射来获取方法,然后获取其所有参数类型,如下所示:
Type[] parameters = method.getGenericParameterTypes();
从那里我遍历parameters
以获取它们各自的类,以便我可以传递正确的数据。 我尝试了以下方法:
Type currentType = parameters[index];
Class<?> clazz = Class.forName(currentType.getClass().getName());
if (clazz.isAssignableFrom(Number.class)) {
//do stuff that is number specific
//EG drill down farther into specific subclass like int,
//double, etc for more exact parsing
} else if (clazz.isAssignableFrom(String.class)) {
//Do stuff that is specific to string
} else {
//Nope, no love here.
}
但是它不能正确检测它什么时候应该是Number
或String
并且总是落在最后的else语句中。 我必须忽略一些非常简单的事情,但是对于我一生来说,我无法确定它可能是什么。
在此先感谢所有。
更新:这是我正在解析的方法存根的一个非常简单的示例。 没什么复杂的。
public void methodWithInt(int integer){
//do something
}
public void methodWithString(String string){
//do something else
}
更新:根据Sotirios Delimanolis
回答,我已经取得了一些进展。
if (currentType instanceof Class) {
Class<?> currentClazz = (Class<?>) currentType;
if (currentClazz.isAssignableFrom(Number.class)) {
// This isn't getting reached for either int or Integer
} else if (currentClazz.isAssignableFrom(String.class)) {
// This IS working correctly for strings
} else {
// Both int and Integer fall here
}
} else {
// Are primitives supposed to be handled here? If so int isn't
// being sent here, but is falling in the the else from the
// condition previous to this one.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.