我正在编写一个方法来打印它传递的每个Object.通过为对象调用Object.toString()方法可以正常工作,但不适用于数组.我可以通过Object.getClass().isArray()方法找出它是否是一个数组,但我不知道如何转换它.
int[] a; Integer[] b; Object aObject = a; Object bObject = b; // this wouldn't work System.out.println(Arrays.toString(aObject)); System.out.println(Arrays.toString(bObject));
解决方法
如果您不知道类型,可以将对象强制转换为Object []并像这样打印(确保它确实是一个数组并且可以转换为Object []).如果它不是Object []的实例,则先使用反射创建一个Object [],然后打印:
private void printAnyArray(Object aObject) { if (aObject.getClass().isArray()) { if (aObject instanceof Object[]) // can we cast to Object[] System.out.println(Arrays.toString((Object[]) aObject)); else { // we can't cast to Object[] - case of primitive arrays int length = Array.getLength(aObject); Object[] objArr = new Object[length]; for (int i=0; i<length; i++) objArr[i] = Array.get(aObject,i); System.out.println(Arrays.toString(objArr)); } } }
测试:
printAnyArray(new int[]{1,4,9,16,25}); printAnyArray(new String[]{"foo","bar","baz"});
OUTPUT:
[1,25] [foo,bar,baz]