如何在Java中获取原始字面量的类型?

huangapple go评论73阅读模式
英文:

How do you get the type of a primitive literal in Java?

问题

我刚刚了解到在长整型数值后面使用"L"来表示它们是长整型,就像在浮点数类型后面使用"f"一样。我想知道当你写成:

long value = 3;

而不是

long value = 3L;

会发生什么。

所以我在想:

编译器会将3视为整数,然后隐式地转换为长整型吗?

然后我尝试使用 instanceof 来检查值为"3"的类型(但我不能使用它,因为它是原始类型),或者使用反射(getClass(),但显然我不能因为它不是引用类型)。有没有办法检查值"3"的类型,或者由于Java是静态类型语言,这是不可能的?

谢谢,
Bernard

英文:

I just learned about using "L" after long values to signify that they're long types, just like when you use "f" after float types. I was wondering what happens when you write;

long value = 3;

instead of

long value = 3L;

So I was wondering;

Does the compiler consider 3 an integer and then just convert it implicitly to a long?

Then I tried to check the type of the value "3" by using instanceof (but I can't use it since it is a primitive type) or reflection (getClass(), but obviously I can't because it isn't a reference type). Is there anyway to check what type the value "3" is or is this impossible since Java is statically typed?

Thanks,
Bernard

答案1

得分: 1

根据Java 14语言规范的第3.10.1节 整数字面值

> 如果整数字面值以ASCII字母Ll(小写的L)作为后缀,则其类型为long;否则其类型为int(参见§4.2.1)。

英文:

According to section 3.10.1 Integer Literals of the Java 14 Language Specification:

> An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

huangapple
  • 本文由 发表于 2020年8月16日 21:26:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63437448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定