Generic Gson Help

37 views
Skip to first unread message

Jacob

unread,
Nov 6, 2008, 3:00:48 PM11/6/08
to google-gson
I have a model

class Envelope<T> {
public int version;
public T data;
}

Many many services share the envelope and I want to provide a shared
method for marshalling it. I have tried the following

protected final <T> String buildResult(T result, int version) {
Envelope<T> env = new Envelope<T>();
env.setData(result);
env.setVersion(version);
return new Gson().toJson(env, new TypeToken<Envelope<T>>() {
}.getType());
}

This compiled but fails a runtime with
java.lang.IllegalArgumentException: Type 'T' is not a Class,
ParameterizedType, or GenericArrayType. Can't extract class.

Is there a way to do this without making the type a parameter? I am
more to willing to say my knowledge of generics in Java is weak.

Jacob

inde...@gmail.com

unread,
Nov 6, 2008, 11:06:54 PM11/6/08
to google-gson
This can not be done. The TypeToken trick needs actual classes, not
type variables.

You would need to change buildResult to take the class or type
parameter corresponding to T.
Reply all
Reply to author
Forward
0 new messages