I want a method that extracts the data from a JSON-object parsed before as the correct type. The JSONObject (rawdata) extends Map, so it looks like this:
private <Type> Type getValue(String key, Type def)
{
if (!rawdata.containsKey(key)) return def;
if (!(rawdata.get(key) instanceof Type)) return def;
return (Type) rawdata.get(key);
}
The instanceof obviously generates a compile-time-error. The parameter def is the default-value, returned if the key is not available or has the wrong type. But def can also be null, so def.getClass() isn’t working.
Any ideas how I can check the content of the Map-entry for the correct type?
Due to type erasure, the only way to handle the case where the default value can be null is to have the method require an additional parmeter of type
Class– which is generally better because it allows the default value to be a subclass of the required type.