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 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 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);
解决方案
The Javadoc for toJson looks to answer your question
typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection, you should use:
Type typeOfSrc = new TypeToken>(){}.getType();
So in your instance.
private static final Type MY_OBJECT_TYPE = new TypeToken>(){}.getType();