2

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.

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

How would I use newInstance(); with the constructor arguments for the class of x and y?
As I mentioned, for that, newInstance() is not sufficient, and you must use getConstructor() to find the appropriate constructor and invoke it. I will add an example in a moment, in the mean time I suggest taking a look at the getConstructor() method in the linked documentation.
There you go. Be sure to pass the appropriate types to getConstructor() that match your object's constructor.
You're welcome. If you feel that this is the correct answer, I'd appreciate it if you clicked the check mark and marked it as the answer. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.