我一直在浏览我在 SO 上看到的答案,到目前为止我找不到任何适合我的解决方案。本质上我只是使用反射来获取一个方法,然后获取它的所有参数类型,如下所示:
Type[] parameters = method.getGenericParameterTypes();
从那里我迭代参数
以获取它们各自的类,以便我可以传递正确的数据。我尝试过以下方法:
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 语句。一定有一些非常简单的东西被我忽略了,但我一生都无法确定它可能是什么。
提前感谢大家。
更新:这是我正在解析的方法 stub 的一个非常简单的示例。这并不复杂。
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.
}
最佳答案
这个
Type currentType = parameters[index];
已经为您提供了参数的类型。
调用
currentType.getClass()
返回 Type
类型的 Class
对象,而不是您想要的。
Class
是 Type
亚型。您可以检查您拥有的 Type
引用是否是 Class
的 instanceof
,然后执行您的 isAssignableFrom
。
关于java - 检查 Java 反射类型的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25793575/