Search code examples
javajava-8primitiveobject-type

typeof in Java 8


If we want to check the datatype of variable in javascript, we can use typeof operator .

Consider this snippet

var c = 'str' ;
console.log(typeof(c)); // string
c = 123 ;
console.log(typeof(c)); // number
c =  {} ;
console.log(typeof(c)) ; // object

I want to achieve the same functionality in Java 8 . Java does not have typeof operator but there's the instanceof operator to check the types.

System.out.println("str" instanceof String);  // true 

Integer a  = 12 ;
System.out.println(a instanceof Integer);


Float f = 12.3f
System.out.println(f instanceof Float); // true

Can we do any better ? Plus instanceof does not support primitive types .

Is there any approaches in java 8 ? Any relevant approaches will be appreciated.


Solution

  • You can use the getClass() method to get the type of the object you are using:

    Object obj = null;
    obj = new ArrayList<String>();
    System.out.println(obj.getClass());
    
    obj = "dummy";
    System.out.println(obj.getClass());
    
    obj = 4;
    System.out.println(obj.getClass());
    

    This will generate the following output:

    class java.util.ArrayList
    class java.lang.String
    class java.lang.Integer
    

    As you see it will show the type of the object which is referenced by the variable, which might not be the same as the type of the variable (Object in this case).

    For primitive types there is no solution available as the problem of knowing the type stored in a variable does not exist. A primitive type variable can hold only values of that type. As you have to define the variable (or parameter) somewhere you already know the type of it and the values it can hold. There is no "base" type for primitive values which you can use similar to the Object type, which is the base type for all objects in java.