I have a method who's definition looks like this:
public static <T> List fromInputStreamToObject(InputStream inputStream, Class<T> clazz) throws Exception{
List objects = null;
try {
if(inputStream!=null){
Reader reader = new BufferedReader(new InputStreamReader(
inputStream));
Type typeOfSrc = new TypeToken<JsonConverter<T>>(){}.getType();
JsonConverter jsonConverter = getGson().fromJson(reader, typeOfSrc);
if(jsonConverter!=null)
objects = jsonConverter.getData();
}
} catch (Exception e) {
throw e;
}
return objects;
}
This doesn't give any compilation error, but
Type typeOfSrc = new TypeToken<JsonConverter<T>>(){}.getType();
gives the run time exception "Type 'T' is not a Class, ParameterizedType, or GenericArrayType. Can't extract class."
How do i use the T to initialize my TypeToken instance?
try this
Type typeOfSrc = type(JsonConverter.class, clazz);
// type(C, A1,...,An) => C<A1,...,An>
static ParameterizedType type(final Class raw, final Type... args)
{
return new ParameterizedType()
{
public Type getRawType(){ return raw; }
public Type[] getActualTypeArguments(){ return args; }
public Type getOwnerType(){ return null; }
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With