How do I pass in a class to make an array of class

2019-08-19 10:13发布

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 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.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-19 10:34

As @andresp said, you can make a new class with an array as a private field. Another option to avoid having to pass a Class<T> as an argument in addition to the type parameter is to replace the array with java.util.ArrayList, which functions just like an array with a few differences.

For example:

public class MyArray {
    private final java.util.ArrayList arr;
    public MyArray(java.util.ArrayList arr) {
        this.arr = arr;
    }

    // Add your additional methods here.
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-08-19 10:59

You can do something like:

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);

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

查看更多
登录 后发表回答