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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.