mercredi 30 août 2017

How to Check if type of Map extends Number

I'm trying to check if a Map<String, T> contains Objects (T) of type Double or Integer.

I don't want to use the actual Objects in the map for checking the class since It's not certain that the Map contains Objects at all.

I can achieve this by doing the following (Assuming the field is containing a Map):

ParameterizedType type = (ParameterizedType) field.getGenericType(); 

isNumeric(type);

/**
 * @param type
 * @return Returns true if type is numeric
 */
private static boolean isNumeric(ParameterizedType type) {
    return  type.getActualTypeArguments()[1].toString().equals("? extends java.lang.Number");
}

It's sufficient for me but it doesn't feel like a clean solution.

However, I can retrieve the Type of the getActualTypeArguments()[1] by doing the following:

Type typeOfSecondGeneric = type.getActualTypeArguments()[1]; // equals '? extends java.lang.Number'

I can't use Number.class.isAssignableFrom(typeOfSecondGeneric); // Class expected

After I researched a bit, I didn't came up with a better solution than doing the String comparison.

What am I getting wrong?

Help is appreciated!





Aucun commentaire:

Enregistrer un commentaire