Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Generics work at compile-time. The reason super-type tokens work, is because (anonymous) inner classes can access the type arguments to their generic superclasses (superinterfaces), which in turn are stored directly in the bytecode metadata.</p> <p>Once your .java source file is compiled, the type parameter <code>&lt;T&gt;</code> is obviously thrown away. Since it is not known at compile time, it cannot be stored in bytecode, so it's erased and Gson can't read it.</p> <p><strong>UPDATE</strong></p> <p>After newacct's answer, I tried to implement what he suggested in his option 2, ie implementing a <code>ParameterizedType</code>. The code looks like this (here is a basic <a href="http://pastebin.com/PV6cP9jc" rel="noreferrer">test</a>):</p> <pre><code>class ListOfSomething&lt;X&gt; implements ParameterizedType { private Class&lt;?&gt; wrapped; public ListOfSomething(Class&lt;X&gt; wrapped) { this.wrapped = wrapped; } public Type[] getActualTypeArguments() { return new Type[] {wrapped}; } public Type getRawType() { return List.class; } public Type getOwnerType() { return null; } } </code></pre> <p>the purpose of this code, is to be used inside <code>getFromJsonList()</code>:</p> <pre><code>public List&lt;T&gt; fromJsonList(String json, Class&lt;T&gt; klass) { Gson gson = new Gson(); return gson.fromJson(json, new ListOfSomething&lt;T&gt;(klass)); } </code></pre> <p>Even if the technique works and is indeed very clever (I didn't know it and I would have never thinked of it), this is the final accomplishment:</p> <pre><code>List&lt;Integer&gt; list = new Factory&lt;Integer&gt;() .getFromJsonList(text, Integer.class) </code></pre> <p>instead of</p> <pre><code>List&lt;Integer&gt; list = new Gson().fromJson(text, new TypeToken&lt;List&lt;Integer&gt;&gt;(){}.getType()); </code></pre> <p>To me, all this wrapping in useless, even if I agree that <code>TypeToken</code>s make the code look nasty :P</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload