jeudi 6 avril 2017

Casting number to other type using class

I have a method with a signature like this:

Object numericCast(Number n, Class<? extends Number> type)

Note: I am sure my code will only ever pass the primitive wrapper types to this method (i.e. Float.class, Integer.class).

If the passed type is large enough to hold the passed Number, I would like to return this number as an instance of the passed class.

Otherwise, I would like to return the original Number.

How can I implement such a method, since I can't cast the argument due to type differences?

Currently, I have:

try {
    double max = c.getClass().getDeclaredField("MAX_VALUE").getDouble(null);
    double val = n.doubleValue();
    double abs = Math.abs(val);
    if(abs >= max) return n;
    //Part 2?
    //Can't do type.cast(n), or valueOf.invoke(null, n). 
} catch (NoSuchFieldException | IllegalAccessException e) {
    ...
}

How would I best implement this? The valueOf methods of the wrapper classes each only accept their respective types, so I can't, for example, pass a double to ???.valueOf.

Would I need to check the type of the class using several ifs and then call n.???Value?





Aucun commentaire:

Enregistrer un commentaire