1

Let's say i have an array encapsulated in an object :

String[] strvls = { "Alessio", "Ale" };
Object container = strvls;

I want to extract back the array from the container object, how can i do ?

I know that is an array checking in this way :

if(container.getClass().isArray()) {
    //Extract the encapsulated array - How ?
}

I can't cast into a String array, because I can't know for sure that the type of the array was String[] ... So i need to cast into a generic type array, Is it possible in Java ?

4

3 回答 3

6

您可以将其转换为Object[]数组:

String[] strvls = { "Alessio", "Ale" };
Object container = strvls;
if (container.getClass().isArray()) {
    Object[] data = (Object[]) container;
    System.out.println(data.length);
}
于 2012-10-06T09:54:05.857 回答
2

与 Karaszi 的回答类似,但可能有一条捷径:

if(container instanceof Object[])
  System.out.println("Array size: " + ((Object[])container).length);

重要提示:这不适用于原始数组。上面的代码有效,因为 String 派生自 Object 类。

于 2012-10-06T09:59:42.020 回答
0

你可以有这样的方法:

private static <T> T[] getArray(Object o){
    return (T[]) o;
}

这将有助于使用泛型类型,并且您可以将任何“未经检查”的编译器警告封装在此方法中。然后你可以这样做:

Object[] array = getArray(container);

如果您对类型一无所知,或者:

String[] array = getArray(container);

如果你知道它是一个字符串数组。

于 2012-10-06T10:02:06.880 回答