Java typeof 运算符
本文介绍如何在 Java 中获取变量或值的数据类型,并列出一些示例代码以理解该主题。
在 Java 中,要获取变量或值的类型,我们可以使用 Object
类的 getClass()
方法。这是执行此操作的唯一方法,与使用 typeof()
方法检查类型的 JavaScript 不同。
由于我们使用了 Object 类的 getClass()
方法,它只适用于对象,而不适用于基元。如果你想获得基元的类型,那么首先使用包装类来转换它们。让我们通过一些例子来理解。
在 Java 中获取变量/值的类型
在这个例子中,我们使用 getClass()
来检查变量的类型。既然这个变量是字符串类型,那么我们就可以直接调用该方法了。请参考下面的示例。
请注意,getClass()
方法返回一个完全限定的类名,在我们的例子中包括一个包名,例如 java.lang.String
。
public class SimpleTesting {
public static void main(String[] args) {
String msg = "Hello";
System.out.println(msg);
System.out.println("Type is: " + msg.getClass());
}
}
输出:
Hello
Type is: class java.lang.String
获取 Java 中任何变量/值的类型
在上面的例子中,我们使用了一个字符串变量并类似地获取了它的类型;我们还可以使用另一种类型的变量,该方法返回所需的结果。请参考下面的示例。
在这个例子中,除了字符串之外,我们还创建了两个变量,整数和字符,并使用了 getClass() 方法。
package javaexample;
public class SimpleTesting {
public static void main(String[] args) {
String msg = "Hello";
System.out.println(msg);
System.out.println("Type is: " + msg.getClass());
// Integer
Integer val = 20;
System.out.println(val);
System.out.println("Type is: " + val.getClass());
// Character
Character ch = 'G';
System.out.println(ch);
System.out.println("Type is: " + ch.getClass());
}
}
输出:
Hello
Type is: class java.lang.String
20
Type is: class java.lang.Integer
G
Type is: class java.lang.Character
getClass()
方法返回类的完整限定名称,包括包名称。如果你只想获取类型名称,可以使用返回单个字符串的 getSimpleName()
方法。请参考下面的示例。
package javaexample;
public class SimpleTesting {
public static void main(String[] args) {
String msg = "Hello";
System.out.println(msg);
System.out.println("Type is: " + msg.getClass().getSimpleName());
// Integer
Integer val = 20;
System.out.println(val);
System.out.println("Type is: " + val.getClass().getSimpleName());
// Character
Character ch = 'G';
System.out.println(ch);
System.out.println("Type is: " + ch.getClass().getSimpleName());
}
}
输出:
Hello
Type is: String
20
Type is: Integer
G
Type is: Character
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。