title: Java how to cast to a generic type
body: <p>This is my class structure</p>
  
  <pre><code>public abstract class SuperClass
  
  public class A extends SuperClass
  
  public class B extends SuperClass
  </code></pre>
  
  <p>Now I have a frame which is going to display a list of A elements or a list of B elements, in order not to duplicate code I want to make it the most generic as possible.
  My idea is to save the class of the elements of the frame in a field:</p>
  
  <pre><code>public class MyFrame extends Frame {
      private final Class type; // type of the elements i'm going to display
      private final DefaultListModel list; // elements to show in a SelectionList
  
      public &lt;T extends SuperClass&gt; MyFrame(final List&lt;T&gt; elementsToDisplay, Class&lt;T&gt; type) {
           this.list = createListModel(elementsToDisplay);
           this.type = type;
      }
  </code></pre>
  
  <p>Now it's possible to call smth like</p>
  
  <pre><code>List&lt;A&gt; list = new LinkedList&lt;&gt;(...);
  MyFrame frame = new MyFrame(list, A.class);
  </code></pre>
  
  <p>My problem is how to use the field <strong><em>type</em></strong>, for example when one item is selected in the frame I want to cast it to type class, but I don't know how. The following lines are pseudo-code</p>
  
  <pre><code>&lt;T extend SuperClass&gt; foo(T item) { ... }
  
  // ----
  
  Object selectedItem = list.get(selectionList.getSelectedIndex());
  [type.class] castedItem = type.cast(selectedItem);
  foo(castedItem);  
  </code></pre>
  
  <p>How can I cast from Object to the class that is holding <strong><em>type</em></strong>?</p>