Search code examples
javaclassprocessing

Is it possible to store a class in a variable in Java?


I'm trying to do something like:

class test {
  Class c;
  c[] array = new array[0];

  test(Class c_) {
   c = c_;
  }
}

It's so that it can be used generally, and that whatever class I put in the class test works. I've tried this exact thing already, but it doesn't seem to work. Is there any way this is possible? I'm also using the IDE Processing if that means anything.


Solution

  • Yes, and no. Yes it is possible to dynamically create an array, but not with your syntax (and you should be using a generic type). Also, note that Java arrays have a fixed length (so a zero element array is not very useful). And Java class names start with a capital letter. Something like,

    class Test<T> {
        private T[] array;
    
        @SuppressWarnings("unchecked")
        Test(Class<T> c, int len) {
            array = (T[]) Array.newInstance(c, len);
        }
    
        public void set(int p, T v) {
            array[p] = v;
        }
    
        public T[] getArray() {
            return array;
        }
    }
    

    Then a basic demonstration of using it,

    public static void main(String[] args) {
        int size = 5;
        Test<String> t = new Test<>(String.class, size);
        for (int i = 0; i < size; i++) {
            t.set(i, String.valueOf(i));
        }
        System.out.println(Arrays.toString(t.getArray()));
    }
    

    Outputs

    [0, 1, 2, 3, 4]