Oyabi
Oyabi

Reputation: 914

Generics with params in constructor and call T method

I have an abstract class and 2 (for now) daughter class.

Main Class :

public abstract class Entite<T> {
    public Entite(int ligne, int colonne, Etat etat) {
        ...
    }
/* Some method here*/
}

Daughter 1 (daughter 2 are almost equals):

public class Cellule extends Entite<Cellule> {
    public Cellule(int ligne, int colonne, Etat etat) {
        super(ligne, colonne, etat);
    }
/** Override some method here */
}

Now I want to use generics in other class.

public class Grille<T extends Entite<T>> {
    protected final T[][] grille;
    public Grille(int dimension, int nbCellulesInitiales, Class<T> classe) {
        grille = (T[][])Array.newInstance(classe, 1); // It's good ?
        Etat etat = Etat.Morte;
        for (int i = 0; i < dimension; i++) {
            for (int j = 0; j < dimension; j++) {
                grille[i][j] = new T(i, j, etat); //How can I create T (Cellule) object ?
            }
        }

Java is new for me so I hope I haven't did idiot error ;)

Upvotes: 1

Views: 87

Answers (2)

newacct
newacct

Reputation: 122429

The more general way is to pass a factory, instead of passing a Class.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213223

You can't create an instance like that using a type parameter. You can't associate new operator with a type parameter, or wildcard parameterized type types. However, since you already have a Class<T> parameter in your constructor, you can use it to get the appropriate constructor using Class#getConstructor method. And then instantiate the object using Constructor#newInstance method passing appropriate argument:

Constructor<T> const = classe.getConstructor(int.class, int.class, Etat.class);

for (int j = 0; j < dimension; j++) {
    grille[i][j] = const.newInstance(i, j, etat); 
}

Upvotes: 3

Related Questions