Is there a way to write a method in Java that will cast generic values according to their type?

Viewed 65

I am trying to write a generic method in Java that checks if a value is within a range. The method below just gets a range to begins with and then I do something with it. I want the method to be able to accept int, double, float... The method below is written badly and incorrectly as I cannot cast the min and max values like that. Is there a nice way to write a generic method like that in Java? Thanks

public static <T> Range getRange(T min, T max)
{
    Range range;
    Class<?> rangeType = min.getClass();

    if(rangeType == Double.class)
    {
        range = Range.between((double) min, (double) max);
    }
    else if(rangeType ==  Integer.class)
    {
        range = Range.between((int) min, (int) max);
    }
    else
    {
        range = Range.between((float) min, (float) max);
    }
    return range;
}
1 Answers

how about trying something like this :

@FunctionalInterface
public interface IRange<T> {    
    Range getRange(T min, T max);
}
public class RangeResolver {
    
    static Map<String, IRange> rangeMap;
    
    static {
        rangeMap = new HashMap<>();
        rangeMap.put(Double.class.getName(), (min, max) -> Range.between((double) min, (double) max));
        rangeMap.put(Integer.class.getName(), (min, max) -> Range.between((int) min, (int) max));
    }
    
    public <T> Range getRange(T min, T max) {
        return rangeMap.getOrDefault(min.getClass().getName(), Double.class.getName()).getRange(min, max);
    }

}
Related