ash*_*ley 43 java typeof primitive-types
Java中是否存在类似"typeof"的函数,它返回原始数据类型(PDT)变量的类型或操作数PDT的表达式?
instanceof 似乎只适用于类类型.
Joã*_*lva 65
请尝试以下方法:
int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());
Run Code Online (Sandbox Code Playgroud)
它将打印:
java.lang.Integer
java.lang.Float
Run Code Online (Sandbox Code Playgroud)
至于instanceof,你可以使用它的动态对应物Class#isInstance:
Integer.class.isInstance(20); // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false
Run Code Online (Sandbox Code Playgroud)
old*_*inb 18
有一种简单的方法,不需要隐式装箱,所以你不会混淆原语和它们的包装器.不能使用isInstance基本类型-例如调用Integer.TYPE.isInstance(5)(Integer.TYPE相当于int.class)将返回false作为5被autoboxed到Integer前手.
获得所需内容的最简单方法(注意 - 技术上在编译时为基元完成,但仍需要评估参数)是通过重载.看我的ideone粘贴.
...
public static Class<Integer> typeof(final int expr) {
return Integer.TYPE;
}
public static Class<Long> typeof(final long expr) {
return Long.TYPE;
}
...
Run Code Online (Sandbox Code Playgroud)
这可以如下使用,例如:
System.out.println(typeof(500 * 3 - 2)); /* int */
System.out.println(typeof(50 % 3L)); /* long */
Run Code Online (Sandbox Code Playgroud)
这依赖于编译器确定表达式类型并选择正确重载的能力.
| 归档时间: |
|
| 查看次数: |
37209 次 |
| 最近记录: |