开发者

Getting unexpected parameter type when calling Method.getParameterTypes()

开发者 https://www.devze.com 2023-03-29 04:30 出处:网络
I have the following class hierarchy: public abstract class NumberRangeParameter<T extends Comparable<T>>

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 i开发者_如何学Cnstance 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消