2012-09-11 119 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 */ 

这依赖于编译器的确定表达式的类型和选择正确的过载的能力。