GSON's toJson function takes a type argument which checks the Type when reflecting the object. This is useful for reflecting objects into a collection.
However, the only way I can find to obtain the Type is through an ugly set of coding contortions:
//used for reflection only
@SuppressWarnings("unused")
private static final List<MyObject> EMPTY_MY_OBJECT = null;
private static final Type MY_OBJECT_TYPE;
static {
try {
MY_OBJECT_TYPE = MyClass.class.getDeclaredField("EMPTY_MY_OBJECT").getGenericType();
} catch (Exception e) {
...
}
}
private List<MyObject> readFromDisk() {
try {
String string = FileUtils.readFileToString(new File(JSON_FILE_NAME), null);
return new Gson().fromJson(string, MY_OBJECT_TYPE);
} catch (Exception e) {
...
}
}
Is there a way of initializing the Type without referencing internal class variables? The pseudocode would looks something like this:
private static final Type MY_OBJECT_TYPE = TypeUtils.generate(List.class, MyObject.class);