1

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?

guardianpt
  • 526
  • 3
  • 8

1 Answers1

2

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

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks, i figured it had something to do with that, Java generics still puzzle me sometimes. By the way, I wonder what kind of error I will get if I invoke the method with a subclass of `Comparable` but not `BigInteger`. – guardianpt Aug 20 '11 at 02:34
  • You will likely not see any compile-time errors (one of the risks of using reflection with generics) but would likely get a class cast exception at run time. – Hovercraft Full Of Eels Aug 20 '11 at 02:36