Given the class <?>, Can I determine if it subclasses a particular type?
I am trying to write a Java function that takes a Class<?> And returns a string that represents a reasonable guess for the corresponding JavaScript type. I / O Example:
in | out --------------------------------- String.class | "string" int.class | "number" double.class | "number" Integer.class | "number" Date.class | "date" (yes, I know that typeof new Date() === 'object') boolean.class | "boolean" Foo.class | "object" Here is what I still have, and it seems to basically work:
String jsType(Class<?> clazz) { if (clazz.equals(String.class) return "string"; if (clazz.equals(boolean.class) return "boolean"; try { clazz.asSubclass(Number.class); return "number"; } catch (Exception e){} try { clazz.asSubclass(Date.class); return "date"; } catch (Exception e){} return "object"; } However, it incorrectly returns a "number" for numeric primitives, for example. int.class , double.class , etc., although it works correctly for wrapper types, Integer.class , etc.
- Is there anything special in the class literature for primitive types?
- Is there a way to write this function, which is better than a set of
if-else, for each class that interests me?
There are two questions. Firstly, the answer is that there is nothing special in the class literature for primitive types except the obvious: they are primitive types. The isPrimitive () method returns true for such types. You seem to expect the primitive types to be subclasses of Number , but that is not what your example shows.
Is there a better way to write a function than a bunch of if-else statements? probably no! Although I would try to avoid using exceptions as a test, exceptions should be reserved for truly exceptional conditions; use isAssignableFrom(Class<?>) instead - although I think this is more a matter of style (and possibly efficiency).
Here's an approach that first normalizes classes, simplifying the jsType method:
Class<?> normalise(Class<?> cls) { if (Number.class.isAssignableFrom(cls) || cls == int.class || cls == long.class || cls == double.class || cls == float.class) { return Number.class; } else if (cls == Boolean.class || cls == boolean.class) { return Boolean.class; } else if (Date.class.isAssignableFrom(cls)) { return Date.class; } else { return cls; } } String jsType(Class<?> cls) { Class<?> normalised = normalise(cls); if (normalised == Number.class) { return "number"; } else if (normalised == Boolean.class) { return "boolean"; } else if (normalised == Date.class) { return "date"; } else if (normalised == String.class) { return "string"; } else { return "object"; } }