bzach
bzach

Reputation: 1

Java Create new Instance of object using Generics OR Class type

I realize there are many similar questions but none seem to get me quite where I need to be.

I am using an object pool, SpritePool, to keep references of AbstractSprites. I create instances of SpritePool, giving it the type of Sprite it should hold. A Sprite extends AbstractSprite. I know the following is redundant, but this is me just trying different things out.

SpritePool bulletPool = new SpritePool<GameBullet>(GameBullet.class);

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.

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.

public class GameSpritePool<T extends AbstractSprite> {

    private Class<T>                clazz;


    public GameSpritePool(Class<T> 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;
    }

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!

Upvotes: 0

Views: 2404

Answers (1)

Nikolay
Nikolay

Reputation: 1949

You should use Factory pattern instead of passing concrete sprite class to pool and do reflection.

Create interface like here

public interface SpriteFactory<T extends AbstractSprite> {
  T createSprite();
}

implement it for all your objects and pass it to your pool

SpritePool bulletPool = new SpritePool<GameBullet>(new GameBulletFactory());

Upvotes: 1

Related Questions