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

可紊 提交于 2020-01-25 06:47:11

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/57261485/how-do-i-pass-in-a-class-to-make-an-array-of-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!