Search code examples
javagenericsparameterized

How to inspect a Parameterized method?


I would like to convert a Number form a String with such a method :

class MathUtils{

    public static <T extends Number> T convert(String str){

       try{
        //convert str depending on the parameter T

       }catch(Exception e){
          e.printStackTrace();
       }
    }
}

Then I call my function with :

 Float f = MathUtils.<Float>convert("2");

Unfortunately, even looking deeply in the debugger, I have no clue how to get this Float parameter. I just can have an hold on Number, but never Float.

There is a way to get the actual parameter of o Collection using ParameterizedType.getActualType(), but what for parameterized method ?

Thank you !


Solution

  • In java, due to type erasure, you cannot infer the generic type like that. You'll have to change your method signature to

    public static <T extends Number> T convert(Class<T> clazz, String str){
    
       if (clazz == Float.class)
       {
           ...
       }
       ...
    }
    

    and call Float f = MathUtils.<Float>convert(Float.class, "2");