In Java, there is no direct built-in function like some dynamic languages (such as Python's type()) to query data types. However, you can use some common methods to determine the type of a variable.
1. instanceof operator
instanceof is an operator in Java that checks whether an object belongs to a specific class. It can be used to determine the actual type of an object.
Example:
String str = "Hello"; if (str instanceof String) { ("str is of type String"); }
2. Obtain data types through class reflection
Java's reflection mechanism can obtain the type of an object at runtime, and the commonly used callgetClass()
method.
Example:
Object obj = "Hello"; ("Type of obj: " + ().getSimpleName());
The above code will output Type of obj: String.
3. getClass() method (only for objects)
You can get the class information of its runtime by calling getClass() via an object, but this only applies to objects (i.e., reference types). For basic data types (such as int, boolean, etc.), they are automatically boxed as object types at runtime.
Example:
int number = 10; (((Object) number).getClass().getSimpleName());
The above methods are common methods used to query variables or object types in different scenarios.
This is the end of this article about the three methods of viewing variable data types in Java. For more related Java to view variable data types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!