Вопрос

In Java how do I create an array of class definitions and create the class from that array?

List<Class> blockArray = new Array<Class>();
blockArray.add(LTetrino.class);

I get stuck when it comes to this, how do I create the class from the classname?

public Tetrino getBlock(int x, int y)
{
    // return new LTetrino(x, y); OLD CODE
    return new blockArray.get(blah);
}

I'm pretty sure I'm doing something wrong here. Thanks in advance.

Это было полезно?

Решение

See Class.newInstance().

For example:

List<Class> blockArray = new ArrayList<Class>();
blockArray.add(LTetrino.class);

// then instantiate an object of the class that was just added
LTetrino block = blockArray.get(0).newInstance();

If your class constructor takes parameters, you can use the getConstructor() method of Class to retrieve the appropriate Constructor, and invoke that instead (it's linked in the docs above), e.g. (assuming LTetrino is a static / top level class and that its constructor takes two int parameters):

Class<? extends LTetrino> cls = blockArray.get(0);
// get constructor
Constructor<? extends LTetrino> ctor = cls.getConstructor(int.class, int.class);
// instantiate by invoking constructor
LTetrino block = ctor.newInstance(x, y);

By the way, I recommend not using a generic type for Class:

List<Class<? extends LTetrino>> blockArray = new ArrayList<Class<? extends LTetrino>>();
blockArray.add(LTetrino.class);

Or at the minimum:

List<Class<?>> blockArray = new ArrayList<Class<?>>();
blockArray.add(LTetrino.class);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top