mardi 29 janvier 2019

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





Aucun commentaire:

Enregistrer un commentaire