簡體   English   中英

檢查Java反射類型的類

[英]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.
}

但是它不能正確檢測它什么時候應該是NumberString並且總是落在最后的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.
}

這個

Type currentType = parameters[index];

已經為您提供了參數的類型。

呼喚

currentType.getClass()

返回類型為TypeClass對象,而不是您想要的類型。

ClassType子類型。 您可以檢查您擁有的Type引用是否是Classinstanceof ,然后執行isAssignableFrom

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM