How can Java determine the type of a variable?
In Java, you can use the instanceof keyword to determine the type of a variable.
For example,
Object obj = "Hello";
if (obj instanceof String) {
System.out.println("obj 是String类型");
} else {
System.out.println("obj 不是String类型");
}
In this code snippet, a variable named obj is first declared and assigned the value “Hello” as a string. Then, the instanceof keyword is used to determine if obj is of type String. If it is, the program outputs that obj is of type String; otherwise, it outputs that obj is not of type String.
In addition to the instanceof keyword, you can also use the getClass() method to get the type of a variable. For example:
Object obj = "Hello";
Class<? extends Object> objType = obj.getClass();
System.out.println("obj 的类型是:" + objType);
In this code snippet, the type of obj is obtained by calling the getClass() method and assigned to the objType variable. Then, the type of obj is printed out using an output statement.
It’s important to note that the getClass() method returns a Class object, not a string. If you need to print out the variable’s type name, you can use the getName() method. For example:
Object obj = "Hello";
Class<? extends Object> objType = obj.getClass();
System.out.println("obj 的类型是:" + objType.getName());
In this code snippet, the getName() method is called to get the type name of obj and print it out. The output shows that the type of obj is java.lang.String.