Java:将对象转换为数组类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1611735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:48:16  来源:igfitidea点击:

Java: Casting Object to Array type

java

提问by Jens

I am using a web service that returns a plain object of the type "Object". Debug shows clearly that there is some sort of Array in this object so I was wondering how I can cast this "Object" to an Array (or similar)?

我正在使用返回“对象”类型的普通对象的 Web 服务。调试清楚地表明这个对象中有某种数组,所以我想知道如何将这个“对象”转换为一个数组(或类似的)?

I tried the following:

我尝试了以下方法:

Collection<String> arr = (Collection<String>) values;
Vector<String> arr = (Vector<String>) values;
ArrayList<String> arr = (ArrayList<String>) values;

But nothing worked. I always get an InvocationTargetException.

但没有任何效果。我总是得到一个 InvocationTargetException。

What am I doing wrong?

我究竟做错了什么?

Edit:

编辑

Sadly, I had to remove the link to the image that showed the output of Eclipse's debugger because it was no longer available. Please do not wonder why in the answers an image is mentioned that is not there anymore.

遗憾的是,我不得不删除指向显示 Eclipse 调试器输出的图像的链接,因为它不再可用。请不要想知道为什么在答案中提到了不再存在的图像。

采纳答案by gustafc

Your valuesobject is obviously an Object[]containing a String[]containing the values.

您的values对象显然是一个Object[]包含一个String[]包含值的对象。

String[] stringValues = (String[])values[0];

回答by Jon Skeet

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

您所拥有的(根据调试图像)是一个包含字符串数组的对象数组。所以你需要这样的东西:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values- if this is already Object[]then you could just use (String[])values[0].

您尚未显示的类型values- 如果已经显示,Object[]则可以使用(String[])values[0].

Of course even with the cast to Object[]you could still do it in one statement, but it's ugly:

当然,即使有演员表,Object[]你仍然可以在一个声明中做到这一点,但它很难看:

String[] strings = (String[]) ((Object[])values)[0];