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);
toJsonlooks like they might answer your question.Type typeOfSrc = new TypeToken<List<MyObject>>(){}.getType();private static final Type MY_OBJECT_TYPE = TypeUtils.generate(List.class, MyObject.class);- have you tried writing your own version ofTypeUtils.generateto implement this proposed interface?org.apache.commons.lang3.reflect.TypeUtils.parameterize(...)See: commons.apache.org/proper/commons-lang/javadocs/api-3.9/org/…