Niko
Niko

Reputation: 4448

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

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

Upvotes: 0

Views: 3596

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

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.

Class is a Type subtype. You can check if the Type reference you have is an instanceof of Class and then perform your isAssignableFrom.

Upvotes: 2

Related Questions