Assuming a generic type declaration (Java)
class Foo {
public T bar;
}
how can I, at runtime, instantiate a Type object that r
I think I understand your question. You want to serialize a Foo
, and you have the class object of T
at runtime (but it's not fixed at compile time). Therefore, the suggested solution in Gson of creating an anonymous subclass of TypeToken
does not work because that requires that the parameterized type (e.g. Foo
) be hard-coded at compile time, and it does not work if you use something like Foo
.
However, let's look at what the TypeToken
method on the Gson site actually accomplishes. You create an object of an anonymous subclass of TypeToken
, and then ask for its type parameter using its getType()
method. A class's superclass is part of its metadata, and includes the generic parameters of its superclass. So at runtime, it can look at its own inheritance hierarchy, and figure out what type parameter you used for TypeToken
, and then returns a java.lang.reflect.Type
instance for that type (which, if it is parameterized, will be a ParameterizedType
instance). Once you get this Type
instance, you are supposed to pass it as the second argument of the toGson()
.
All we need to do is find another way to create this instance of ParameterizedType
. ParameterizedType
is an interface, but unfortunately the public Java API does not provide any concrete implementations or any way to create a ParameterizedType
dynamically. There appears to be a class called ParameterizedTypeImpl
, in the private Sun APIs and in the Gson code that you can use (e.g. here). You can simply copy the code and rename it into your own class. Then, to create a Type
object representing Foo
at runtime, you can just do something like new ParameterizedTypeImpl(Foo.class, new Type[]{String.class}, null)
(untested)