不使用 getClass() 或 instanceof 的 typeOf

typeOf without using getClass() or instanceof

我目前正在尝试使用 System.out.print 给出整数 x 的类型。然而,据我发现,唯一类似于 typeOf 的函数是 getClass,它不适用于 int,或者 instanceof,它似乎只适用于 if。有没有其他我可以尝试的命令,或者我是否坚持使用 System.out.print("Integer")

注意 Java 是静态类型语言。无需在运行时检查变量原始类型,因为它在编译时已知且无法更改。例如,如果您声明

int x = 5;

那么 x 只能是 int,所以尝试做类似 typeof(x) 的事情(就像在其他一些语言中一样)是没有意义的。

您可以将变量类型概括为 Object 引用类型:

int x = 5;
Object obj = x;

但即使在这种情况下 obj 也不会是 int。在这种情况下,Java 编译器会自动将您的 x 装箱为 Integer 类型,因此 obj.getClass().getName() 将 return java.lang.Integerobj instanceof Integer 将return 正确。

通常,如果您知道类型,就没有合理的理由这样做,您不需要函数来为您解决。

只有当您无法确定类型时,这才有用,例如因为你在学习,类型不明显。您可以使用这样的重载函数来实现它。

public static void main(String[] args) {
    byte b = 1;
    byte a = 2;
    System.out.println("The type of a+b is "+typeOf(a+b));
    long l = 1;
    float f = 2;
    System.out.println("The type of l+f is "+typeOf(l+f));
}
public static String typeOf(byte b) {
    return "byte";
}
public static String typeOf(char ch) {
    return "char";
}
public static String typeOf(short s) {
    return "short";
}
public static String typeOf(int i) {
    return "int";
}
public static String typeOf(long i) {
    return "long";
}
public static String typeOf(float i) {
    return "float";
}
public static String typeOf(double i) {
    return "double";
}
public static String typeOf(boolean b) {
    return "boolean";
}
public static String typeOf(Object o) {
    return o.getClass().getName();
}

打印

The type of a+b is int
The type of l+f is float