title: Generic Method to Create Multiple Fragments
body: <p>I want to write a method that creates multiple fragments for me and I am not sure how to do this.  After a few attempts I got more confused.</p>
  
  <p>Here is how I typically and creating two fragments</p>
  
  <pre><code>private void createFragDog(Animals animals) {
      DogFragment frag = DogFragment.newInstance(ArrayList&lt;Dogs&gt; animals.getDogs());
      ...    
      *frag.(do fragment manager stuff and commit())*
      ...
  }
  </code></pre>
  
  <p>Second call to create fragment</p>
  
  <pre><code>private void createFragCat(Animals animals) {
      CatFragment frag = CatFragment.newInstance(ArrayList&lt;Cats&gt; animals.getCats());
      ...    
      *frag.(do fragment manager stuff and commit())*
      ...
  }
  </code></pre>
  
  <p>Being that the newInstance method is static I can't seem to figure out how to make a generic method and just pass in the class types. Also the object passed into newInstance is not always an array. Here is my attempt:</p>
  
  <pre><code>private &lt;T,E&gt; void animalFragments(Class&lt;T&gt; frag, Class&lt;E&gt; animalType, Object obj){
      if (obj == null) return;
      if (obj instanceof List&lt;?&gt;) {
          if (((List&lt;E&gt;)obj).isEmpty()) return;
      }
  
      try {
          T fragment = (T) frag.newInstance();
          ?? Not sure what to do now or how to call up method that is static but specific to both.
  
      } catch (InstantiationException e) {
          e.printStackTrace();
      } catch (IllegalAccessException e) {
          e.printStackTrace();
      }
  }
  </code></pre>