Casting an object array to a string array

at 2008-07-19 in Further reading by friebe (0 comments)

While testing the new EASC server and client implementations we're currently working on, we asked ourselves how to cast an object array to, for example, a string array.

The following is an array of objects consisting solely of strings:

  Object[] strings= new Object[] { "Hello", "World" };

The first thing we tried was to cast it via (String[])strings. This is legal sourcecode but will raise a java.lang.ClassCastException in Java, and a System.InvalidCastException in C#, both at runtime.



Java
The correct way to do this is to create a new string array and copy the elements:
  String[] list= new String[strings.length];
System.arraycopy(strings, 0, list, 0, strings.length);
To do this reflectively, the java.lang.reflect.Array class can be used:
  Array.newInstance(String.class, strings.length);

Funny enough, the return type for Array.newInstance is Object (and not Object[]).



C#
The same goes for C#, except for slight differences in the method names:
  // Hard-coded
String[] list= new String[strings.Length];
strings.CopyTo(list, 0);

// Reflective
Array.CreateInstance(typeof(String), strings.Length);



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases

Related

Find related articles by a search for «Casting».