2012-09-11 323 views
29

在Java中是否有一個類似「typeof」的函數,它返回原始數據類型(PDT)變量的類型或操作數PDT的表達式?如何確定原始變量的原始類型?

instanceof似乎只適用於類類型。

+1

你在尋找一個代表'int','long'等的類嗎? – dasblinkenlight

+3

不知道它的類型,你不能有一個基本的數據類型。它必須裝入一個'Number'類型以便你不知道它,在這種情況下你可以使用'instanceof'。 – Thor84no

+0

@ Thor84no是的,你可以用反射 – Bohemian

回答

50

嘗試以下操作:

int i = 20; 
float f = 20.2f; 
System.out.println(((Object)i).getClass().getName()); 
System.out.println(((Object)f).getClass().getName()); 

它會打印:

java.lang.Integer 
java.lang.Float 

至於instanceof,你可以使用它的動態對應Class#isInstance

Integer.class.isInstance(20); // true 
Integer.class.isInstance(20f); // false 
Integer.class.isInstance("s"); // false 
+0

還沒有還沒試過但這是我在找什麼。謝謝。 – ashley

13

有一個簡單的方式,不需要隱式拳擊,所以你不會感到困惑吐溫原語和他們的包裝。您不能使用isInstance作爲原始類型 - 例如呼叫Integer.TYPE.isInstance(5)Integer.TYPE相當於int.class)將返回false,因爲5被自動複製到Integer之前。

最簡單的方式來獲得你想要的東西(注 - 這是在編譯時的原語技術上做了,但它仍然需要論證的評價)是通過超載。請參閱我的ideone paste

... 

public static Class<Integer> typeof(final int expr) { 
    return Integer.TYPE; 
} 

public static Class<Long> typeof(final long expr) { 
    return Long.TYPE; 
} 

... 

這可用於如下,例如:

System.out.println(typeof(500 * 3 - 2)); /* int */ 
System.out.println(typeof(50 % 3L)); /* long */ 

這依賴於編譯器的確定表達式的類型和選擇正確的過載的能力。