5

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); 
5
  • 1
    Have you tried writing your method with the interface you're looking at and run into a problem? Commented Nov 20, 2014 at 20:48
  • @Chris Sorry, I don't understand your question. Commented Nov 20, 2014 at 20:49
  • 1
    @patstuart the javadoc for toJson looks like they might answer your question. Type typeOfSrc = new TypeToken<List<MyObject>>(){}.getType(); Commented Nov 20, 2014 at 20:52
  • @patstuart I'm referring to your pseudocode - private static final Type MY_OBJECT_TYPE = TypeUtils.generate(List.class, MyObject.class); - have you tried writing your own version of TypeUtils.generate to implement this proposed interface? Commented Nov 20, 2014 at 20:54
  • Actually in 2019 there is such a thing that is almost exactly what you expressed in the pseudocode: org.apache.commons.lang3.reflect.TypeUtils.parameterize(...) See: commons.apache.org/proper/commons-lang/javadocs/api-3.9/org/… Commented Aug 27, 2019 at 13:37

2 Answers 2

5

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<Collection<Foo>>(){}.getType(); 

So in your instance.

private static final Type MY_OBJECT_TYPE = new TypeToken<List<MyObject>>(){}.getType(); 
Sign up to request clarification or add additional context in comments.

Comments

1

It is also possible to do like this:

 private static final Type MY_OBJECT_TYPE = TypeToken.getParameterized(List.class, MyObject.class).getType(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.