我如何传入一个类以组成一个类数组?

问题描述:

我想创建一个对数组执行不同方法的类(数组)。到目前为止,我所拥有的是针对不同类型的数组(int,字符串等)的重载构造函数。但是,该类也需要创建一个类数组,那么如何传递一个类名并让我的Array类创建该类的数组?

I want to create a class (Array) that performs different methods on arrays. What I have so far is overloaded constructors for different types of arrays (ints, strings, etc). However this class will also need to create an array of classes, so how could I pass in a class name and have my Array class create an array of that class?

I可以为我知道的类编写硬代码,但我想使我的Array类具有足够的通用性,以便将来与我制作的任何类一起使用。

I could just hard code it in for the class I know I will make an array of but I want to make my Array class versatile enough to have this work with any class I make in the future.

您可以执行以下操作:

public class Array<T> {
    private final T[] arr;

    public Array(final int size, final Class<T> clazz) {
        this.arr = createArray(size, clazz);
    }

    private T[] createArray(final int size, final Class<T> clazz) {
        return (T[]) java.lang.reflect.Array.newInstance(clazz, size);
    }
}

您可以使用调用实例化:

which you can call instantiate by using:

final Array<String> strings = new Array<>(5, String.class);

我也建议为您的班级使用一个不同的名称,即 Array 已被Java API使用。

I would also suggest a different name for your class as Array is already used by the Java API.