Skip to content
Advertisement

Casting to array type using reflection

I find myself in a situation where it seems I would need to be able to cast an Object that is an array of some other, non-primitive type, into its concrete array type, to pass to a generic.

The same thing is trivial to get to work with non-array types: desiredType.cast(o) yields an object of the correct type.

Would someone be so kind to explain either how to do this with arrays, OR why this would never work?

A demonstration of what I’m attempting to do:

import java.lang.reflect.Array;
import java.util.Arrays;

public class Main
{
  public static <T> void testT(T o)
  {
    System.out.println("testT called with " + o + " (" + o.getClass() + ")");
  }

  public static void test(Object o)
  {
    testT(o.getClass().cast(o));
  }

  public static void main(String[] args) throws ClassNotFoundException
  {
    test(new Integer(5));

    Class<?> type = Class.forName("java.lang.Integer");
    Object array = Array.newInstance(type, 2);

    Class<?> arrayType = array.getClass();
    Object[] copy = Arrays.copyOf(arrayType.cast(array), Array.getLength(array)); // NOPE. (casting is optional)

    System.out.println(copy);
  }
}

Advertisement

Answer

You can instead cast it to Object[] if you want to keep it dynamic and it will work:

Object[] copy = Arrays.copyOf((Object[])arrayType.cast(array), Array.getLength(array));

Under the hood it will copy the array as is, i.e. the copy will become an Integer[] for your given example.

If it’s even more generic what you want to do, you could also check whether a given type is actually an array, before casting, e.g. in your example you could use arrayType.isArray() for that.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement