简体   繁体   English

检查Java反射类型的类

[英]Checking the class of a Java Reflection Type

I've been going through the answers I've seen on SO and thus far I can't find any solutions that work correctly for me. 我一直在寻找在SO上看到的答案,到目前为止,我找不到适合我的任何解决方案。 Essentially I'm just using reflection to get a method, and then get all its parameter types like this: 本质上,我只是使用反射来获取方法,然后获取其所有参数类型,如下所示:

Type[] parameters = method.getGenericParameterTypes();

From there I am iterating through the parameters to get their respective classes so I can pass the correct data. 从那里我遍历parameters以获取它们各自的类,以便我可以传递正确的数据。 I've tried the following: 我尝试了以下方法:

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.
}

But it doesn't correctly detect when it should be a Number or String and always falls into the last else statement. 但是它不能正确检测它什么时候应该是NumberString并且总是落在最后的else语句中。 There must be something really simple that I'm overlooking, but for the life of me I cannot determine what it could be. 我必须忽略一些非常简单的事情,但是对于我一生来说,我无法确定它可能是什么。

Thanks to all in advance. 在此先感谢所有。

Update: Here is a really simple example of a method stub I'm parsing. 更新:这是我正在解析的方法存根的一个非常简单的示例。 It isn't anything complicated. 没什么复杂的。

public void methodWithInt(int integer){
    //do something
}

public void methodWithString(String string){
    //do something else
}

Update: Based on Sotirios Delimanolis answer I've made some progress. 更新:根据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.
}

This 这个

Type currentType = parameters[index];

already gives you the type of the parameter. 已经为您提供了参数的类型。

Calling 呼唤

currentType.getClass()

returns a Class object for the type Type , not what you want. 返回类型为TypeClass对象,而不是您想要的类型。

Class is a Type subtype. ClassType子类型。 You can check if the Type reference you have is an instanceof of Class and then perform your isAssignableFrom . 您可以检查您拥有的Type引用是否是Classinstanceof ,然后执行isAssignableFrom

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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