title: Java Create new Instance of object using Generics OR Class type
body: <p>I realize there are many similar questions but none seem to get me quite where I need to be.</p>
  
  <p>I am using an object pool, <code>SpritePool</code>, to keep references of <code>AbstractSprites</code>. I create instances of SpritePool, giving it the type of <code>Sprite</code> it should hold. A Sprite extends AbstractSprite. I know the following is redundant, but this is me just trying different things out.</p>
  
  <pre><code>SpritePool bulletPool = new SpritePool&lt;GameBullet&gt;(GameBullet.class);
  </code></pre>
  
  <p>Within the pool (SpritePool) I need to be able to create new instances of the object the pool is holding. So, in using the example above, the bulletPool must be able to create new instances of a GameBullet if there are no current GameBullet objects available within the pool. </p>
  
  <p>In the following code, I have tried to use reflection (really have no clue what I am doing) to create a new instance of the Class type. I have read that I could possibly use abstract factories for doing what I want but again, I am unsure how to do so. </p>
  
  <pre><code>public class GameSpritePool&lt;T extends AbstractSprite&gt; {
  
      private Class&lt;T&gt;                clazz;
  
  
      public GameSpritePool(Class&lt;T&gt; clazz) {
  
          this.clazz = clazz;
      }
  
  
      /**
       * Creates a new instance object of type T. This object can later be borrowed
       * from the pool if it is not in use.
       * 
       * @return The object of type T that was created
       */
      public AbstractSprite create() {
          try {
              Class[] args = new Class[6];
              args[0] = TransformableContent.class;
              args[1] = ResourceFinder.class;
              args[2] = float.class;
              args[3] = float.class;
              args[4] = float.class;
              args[5] = float.class;
              Constructor constructor = clazz.getConstructor(args);
              return (AbstractSprite)constructor.newInstance((object)args);
          } catch (Exception e) {
              e.printStackTrace();
          }
          return null;
      }
  </code></pre>
  
  <p>If it is any help, the AbstractPool's constructor takes 2 parameters while each Sprite takes 6 parameters. A Sprite's parameter requirements may change but it is unlikely and I would rather work around that then not be able to create objects at all.
  Any help is greatly appreciated!</p>