漂亮的打印数组对象,而不是对象数组?
所以,我已经发现了
Arrays.toString(arr);
所以不要让我指出 这个问题。
我的问题有点不同。在这种情况下,我没有指向相关数组的本机数组指针。我将它作为对象指针,它可以是任何类型的数组(原始或其他类型)。在这种情况下,我可以通过将 Object 指针转换为 Object[] 来使用上面的 toString() 方法。但是,如果指针是原始数组,它将引发运行时异常并崩溃。所以?
示例:
double test[] = {1, 2, 3, 4};
Object t = test;
// Now how do I pretty print t as an array with no access to test?
我用这个解决了我的问题:
public String unkObjectToString(Object o) {
if(!o.getClass().isArray()) return o.toString();
int len = Array.getLength(o);
String ret = "[";
for(int i = 0; i < len; i++) {
Object q = Array.get(o, i);
ret += unkObjectToString(q);
if(i == len - 1)
ret += "]";
else
ret += ", ";
}
return ret;
}
So, I've already discovered
Arrays.toString(arr);
So don't point me to this question.
My problem is just a tiny bit different. In this case, I don't have a native array pointer to the array in question. I have it as an Object pointer, and it could be an array of any type (primitive or otherwise). In this case, I can use the above toString() method by casting the Object pointer to Object[]. However, if the pointer is a primitive array, it will throw a runtime exception and crash. So?
Example:
double test[] = {1, 2, 3, 4};
Object t = test;
// Now how do I pretty print t as an array with no access to test?
I solved my problem with this:
public String unkObjectToString(Object o) {
if(!o.getClass().isArray()) return o.toString();
int len = Array.getLength(o);
String ret = "[";
for(int i = 0; i < len; i++) {
Object q = Array.get(o, i);
ret += unkObjectToString(q);
if(i == len - 1)
ret += "]";
else
ret += ", ";
}
return ret;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你必须测试并投射。
您可以通过反射来完成此操作,但最终不会更干净,尽管会少几行代码。
You have to test and cast.
You could do this via reflection, but it would not be any cleaner in the end, although it would be a few lines of code less.
ArrayUtils.toString(arrayObj)
(commons-lang) -完全符合您的要求(还处理多维数组)。只需下载 commons-lang jar 并将其添加到您的类路径中即可。ArrayUtils.toString(arrayObj)
(commons-lang) - does exactly what you want (also handles multi-dimensional arrays). Simply download the commons-lang jar and add it to your classpath.