2011-02-11 75 views
3

實施例:Java:如何確定對象數組中的對象的類型?

Object[] x = new Object[2]; 
x[0] = 3; // integer 
x[1] = "4"; // String 
System.out.println(x[0].getClass().getSimpleName()); // prints "Integer" 
System.out.println(x[1].getClass().getSimpleName()); // prints "String" 

這使我驚奇:第一對象元素是Integer類的實例?或者它是一個原始數據類型int?有區別,對吧?

所以,如果我想確定第一個元素的類型(是一個整數,雙精度,字符串等),該怎麼做?我使用x[0].getClass().isInstance()? (如果是,如何?),還是我使用別的東西?

回答

4

您想使用instanceof運算符。

例如:

if(x[0] instanceof Integer) { 
Integer anInt = (Integer)x[0]; 
// do this 
} else if(x[0] instanceof String) { 
String aString = (String)x[0]; 
//do this 
} 
5

intInteger只有一個Integer之間的差異可以進入一個Object []但自動裝箱/拆箱使得它難以確定下來。

一旦你把你的價值在數組中,它被轉換爲Integer,它的起源被遺忘。同樣,如果您聲明int []並將其放入Integer,它將被當場轉換爲int,並且不會保留Integer的痕跡。

+0

+1通過解釋的問題題 :) – Dinei 2014-10-12 17:26:28

5

x是一個對象數組 - 因此它不能包含基元,只包含對象,因此第一個元素的類型是Integer。它會成爲自動裝箱的整數,如@biziclop說

要檢查一個變量的類型,使用instanceof

if (x[0] instanceof Integer) 
    System.out.println(x[0] + " is of type Integer") 
3

你問不算什麼,但如果有人想確定類型允許在一個陣列對象:

Oject[] x = ...; // could be Object[], int[], Integer[], String[], Anything[] 

Class classT = x.getClass().getComponentType();