我已经查看了我在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.
}