舉個栗子來說明,寫出通用的輸出方法:
- 數組類型,將元素逐個輸出
- 其他類型直接輸出
public static void printObject(Object obj) {
Class clazz = obj.getClass();
if(clazz.isArray()) {
int len = Array.getLength(obj); // java.lang.reflect.Array
for(int i = 0; i < len; i++)
System.out.print(Array.get(obj, i) + " ");
System.out.println();
}
else
System.out.println(obj);
}
注意:數組只有在元素類型相同、維度也相同時,類型才相同。
new int[3].getClass() == new int[4].getClass()
new int[3].getClass() != new int[3][1].getClass()