How do you know a variable type in java?

后端 未结 7 1752
野性不改
野性不改 2020-11-30 18:07

Let\'s say I declare a variable:

String a = \"test\";

And I want to know what type it is, i.e., the output should be java.lang.String

7条回答
  •  再見小時候
    2020-11-30 19:01

    I think we have multiple solutions here:

    • instance of could be a solution.

    Why? In Java every class is inherited from the Object class itself. So if you have a variable and you would like to know its type. You can use

    • System.out.println(((Object)f).getClass().getName());

    or

    • Integer.class.isInstance(1985); // gives true

    or

    • isPrimitive()

      public static void main(String[] args) {
      
       ClassDemo classOne = new ClassDemo();
       Class classOneClass = classOne();
      
       int i = 5;
       Class iClass = int.class;
      
       // checking for primitive type
       boolean retval1 = classOneClass.isPrimitive();
       System.out.println("classOneClass is primitive type? = " + retval1);
      
       // checking for primitive type?
       boolean retval2 = iClass.isPrimitive();
       System.out.println("iClass is primitive type? = " + retval2);
      }
      

    This going to give us:

    1. FALSE
    2. TRUE

    Find out more here: How to determine the primitive type of a primitive variable?

    https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

    http://docs.oracle.com/cd/E26806_01/wlp.1034/e14255/com/bea/p13n/expression/operator/Instanceof.html

提交回复
热议问题