guardianpt
guardianpt

Reputation: 536

Getting unexpected parameter type when calling Method.getParameterTypes()

I have the following class hierarchy:

public abstract class NumberRangeParameter<T extends Comparable<T>> 
extends ComplexParameter{

    private T lower;

    public void setLower(T lower) {
        this.lower = lower;
    }

}
public class IntegerRangeParameter extends NumberRangeParameter<BigInteger> {}

Now, if I run this (irp is an instance of IntegerRangeParameter):

Method[] methods = irp.getClass().getMethods();
for (Method m : methods) {
    Class<?>[] parameterTypes = m.getParameterTypes();
}

If I step this code on the debugger and evaluate parameterTypes I get [interface java.lang.Comparable], but I was expecting it to be BigInteger...

Can someone explain why this happens?

Upvotes: 1

Views: 582

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

You're running into the Type Erasure issue which is inherent when using Java generics due to the requirement for backward compatibility. Generic parameters are mainly there for compile-time type checking, and the information is lost (for the most part) at run time. Please check out the link provided for more.

Edit 1
Also please check out this similar SO thread: get-type-of-a-generic-parameter-in-java-with-reflection

Upvotes: 2

Related Questions