如何确定一个原始variables的原始types?

在Java中是否有types的函数返回原始数据types(PDT)variables的types或操作数PDT的expression式?

instanceof似乎只适用于类的types。

尝试以下操作:

 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 ,你可以使用它的dynamic对手Class#isInstance

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

有一个简单的方法,不需要隐式装箱,所以你不会在基元和它们的包装之间混淆。 你不能使用isInstance作为原始types – 例如调用Integer.TYPE.isInstance(5)Integer.TYPE等价于int.class )将返回false因为5被自动装箱到一个Integer之前。

最简单的方法就是通过重载来获得你想要的东西(注意 – 它在技术上是在编译时完成原语的,但是仍然需要评估参数)。 看我的ideone贴 。

 ... 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 */ 

这依赖于编译器确定expression式的types并select正确的重载的能力。