title: Java - Generic Static Methods
body: <p>I have been trying to understand whether it is possible to make a method which infers a generic type based on the return class and calls a static method of that generic type.</p>
  
  <p>i.e. Below I create 2 classes both of which implement the getInstances and getAllInstances methods. I then attempt to create use the methods from a generic wrapper. It appears that the super class method is always being run regardless of the return type.</p>
  
  <p>For example,</p>
  
  <pre><code>public class ParentClass {
  
      public ParentClass(){}
  
      public static &lt;T extends ParentClass&gt; T getInstance(){
          return (T) new ParentClass();
      }
  
      public static &lt;T extends ParentClass&gt; List&lt;T&gt; getAllInstances(){
          ArrayList&lt;ParentClass&gt; parents = new ArrayList&lt;ParentClass&gt;();
  
          for(int i=0;i&lt;5;i++){
              parents.add(new ParentClass());
          }
  
          return (List&lt;T&gt;) parents;
      }
  
  }
  </code></pre>
  
  <p>SubclassA</p>
  
  <pre><code>public class SubclassA extends ParentClass{
  
       public SubclassA(){}
  
      @SuppressWarnings("unchecked")
      public static SubclassA getInstance(){
           return new SubclassA();
      }
  
      @SuppressWarnings("unchecked")
      public static List&lt;SubclassA&gt; getAllInstances(){
          ArrayList&lt;SubclassA&gt; parents = new ArrayList&lt;SubclassA&gt;();
  
            for(int i=0;i&lt;5;i++){
               parents.add(new SubclassA());
            }
  
           return parents;
        }
   }
  </code></pre>
  
  <p>Wrapper - Shows the problem</p>
  
  <pre><code> public class Wrapper {
  
      public Wrapper(){
          // ... some other stuff
      }
  
      public &lt;T extends ParentClass&gt; T getInstance(){
          return T.getInstance();
      }
  
      public &lt;T extends ParentClass&gt; List&lt;T&gt; getAllInstances(){
          return T.getAllInstances();
      }
  
      public static void main(String... args){
          Wrapper wrapper = new Wrapper();
  
          SubclassA subclassA = wrapper.getInstance();
          ParentClass parentClass = wrapper.getInstance();
  
          System.out.println(subclassA.getClass().getName());
          System.out.println(parentClass.getClass().getName());
      }
  
   }
  </code></pre>
  
  <p>When running Wrapper I get the following error:</p>
  
  <p>Exception in thread "main" java.lang.ClassCastException: ParentClass cannot be cast to SubclassA
      at Wrapper.main(Wrapper.java:20)</p>
  
  <p>Can I do this in Java?</p>