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:

JavaScript

Advertisement

Answer

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

JavaScript

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