Assuming a generic type declaration (Java)
class Foo {
public T bar;
}
how can I, at runtime, instantiate a Type object that r
The usual way around type erasure is:
class Foo {
Class clazz;
public Foo(Class c) {
clazz = c;
}
public T bar {
return clazz.newInstance();
}
}
If there's no no-args constructor for your T, you can do something fancier using reflection on the Class object; once you have an instance of Class, you can get an instance.
I faced exactly this problem too with gson. I ended up with this:
public class JsonWrapper {
private String className;
private String json; // the output of the gson.toJson() method
}
And when I needed to deserialise, I did a Class.forName(className) then I had all I needed to call the fromJson() method of the gson library.
I couldn't believe gson did not support this natively - it seems like such an obvious thing to want to do... get some json and turn that into an object without knowing which class it is beforehand.