gpt4 book ai didi

java - 如何在 Java 中打印原始变量的类型

转载 作者:行者123 更新时间:2023-12-05 08:43:32 24 4
gpt4 key购买 nike

我想知道我的类中的变量类型,例如:

int x=1;  
char c=5;
System.out.println(x+c);// out put is 6

但是我想知道x+c的类型,是属于integer还是character?并且还想在控制台中打印结果。

有什么方法可以找到类型吗?请帮我提供最佳答案。

最佳答案

Is there any method to find the type?

那么,从研究的角度来看,您可以阅读 Java Language Specification .特别是,section 15.18.2解释 + 运算符的工作原理。

如果您只想从执行时的角度来看,有两种选择:

  • 您可以自动装箱,然后查看装箱类型是什么:

    Object o = x + c;
    System.out.println(o.getClass()); // java.lang.Integer
  • 您可以编写一个为所有 原始类型重载的方法,然后查看编译器选择哪个:

    System.out.println(getCompileTimePrimitiveClass(x + c));
    ...
    private static Class getCompileTimePrimitiveClass(int x)
    {
    return int.class;
    }

    private static Class getCompileTimePrimitiveClass(char x)
    {
    return char.class;
    }

    private static Class getCompileTimePrimitiveClass(byte x)
    {
    return byte.class;
    }

    // etc

关于java - 如何在 Java 中打印原始变量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28475119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com