How to get the data type of a variable in Java?

In Java, the type of a variable can be obtained using the reflection mechanism. You can use methods provided by the Class class to retrieve the type of a variable, as shown below:

  1. By using the getClass() method, you can retrieve the type of a variable through the object’s getClass() method.
String str = "Hello";
Class<? extends String> strClass = str.getClass();
System.out.println(strClass);
  1. You can use the TYPE field of wrapper classes to get the corresponding Class object for primitive data types.
int num = 10;
Class<Integer> numClass = Integer.TYPE;
System.out.println(numClass);
  1. By using the getType() method in the Field class, you can retrieve the type of a variable. It’s important to note that this method should be used in reflection.
import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws NoSuchFieldException {
        String str = "Hello";
        Field field = str.getClass().getField("value");
        Class<?> fieldType = field.getType();
        System.out.println(fieldType);
    }
}

Please note that the above method retrieves the runtime type of a variable, which is the actual stored type. If it is a generic type, the specific generic parameter type cannot be obtained. If you need to retrieve the declared type of a variable, you can use reflection.

bannerAds