title: Generic method to cast from Object to typed instance of List
body: <p>Let's assume, there is a method that returns an <code>Object</code>, but we know it is some sort of typed <code>List</code> (e.g. <code>LinkedList&lt;Long&gt;</code> or <code>ArrayList&lt;String&gt;</code>):</p>
  
  <pre><code>public abstract Object open();
  </code></pre>
  
  <p>Directly using its return value</p>
  
  <pre><code>List&lt;Long&gt; result = (List&lt;Long&gt;)dialog.open();
  </code></pre>
  
  <p>will cause a warning such as:</p>
  
  <p><em>Type safety: Unchecked cast from Object to List</em></p>
  
  <hr>
  
  <p>To overcome this problem, we can cast to <code>List&lt;?&gt;</code> and then check each list item individually:</p>
  
  <pre><code>List&lt;?&gt; result = (List&lt;?&gt;)dialog.open();
  List&lt;Long&gt; safeResult = new LinkedList&lt;Long&gt;();
  
  for (Object obj: result) {
     if (obj instanceof Long) {
        safeResult.add((Long)obj);
     }
  }
  </code></pre>
  
  <hr>
  
  <p>Now I thought, wouldn't it be nice to have a generic method that can cast an <code>Object</code> (that is known to contain a <code>List</code>) to any typed instance of <code>List</code>.</p>
  
  <p>This is the closest I could get:</p>
  
  <pre><code>private &lt;T&gt; List&lt;T&gt; doSafeCast(Object listObject, Class&lt;T&gt; type) {
    List&lt;T&gt; result = new LinkedList&lt;T&gt;();
  
    if (listObject instanceof List) {
       List&lt;?&gt; list = (List&lt;?&gt;)listObject;
  
       for (Object obj: list) {
          if (type.isInstance(obj)) {
             result.add(type.cast(obj));
          }
       }
    }
  
    return result;
  }
  </code></pre>
  
  <p>Now I can use it like this:</p>
  
  <pre><code>List&lt;Long&gt; safeResult = this.doSafeCast(dialog.open(), Long.class);
  </code></pre>
  
  <p>However, now I am bound to have <code>LinkedList</code>s as result only.</p>
  
  <hr>
  
  <p><strong>Is it possible to specify the list type by passing an additional parameter, too?</strong></p>
  
  <p>I would want to to something like this:</p>
  
  <pre><code>List&lt;Long&gt; safeResult = this.doSafeCast(dialog.open(), Long.class, ArrayList.class);
  
  List&lt;String&gt; anotherSafeResult = this.doSafeCast(anotherDialog.open(), String.class, LinkedList.class);
  </code></pre>
  
  <p>I know that all this seems overly complicated and I could just add <code>@SuppressWarnings("unchecked")</code> to my initial unsafe cast, if I were sure that the dialog will always return the desired type. But I came up with this idea of having a general method to do such safe casts and now I want to know, if this is possible at all. So please don't suggest other solutions, I just want to learn about using generics a little more, here. :-) Thank you.</p>