Is there a way to output the java data type to the console?

后端 未结 5 1198
灰色年华
灰色年华 2021-01-31 15:02

I\'m trying to debug a program I inherited. This program contains Strings, array lists and collections, lots of casting between types, and I need to do some String manipulations

相关标签:
5条回答
  • 2021-01-31 15:29

    instance.getClass() is the way to go if you just want to print the type. You can also use instanceof if you want to branch the behaviour based on type e.g.

    if ( x instanceof String )
    {
       // handle string
    }
    
    0 讨论(0)
  • 2021-01-31 15:34

    For any object x, you could print x.getClass().

    0 讨论(0)
  • 2021-01-31 15:35

    Use the getClass() method.

    Object o;
    System.out.println(o.getClass());
    
    0 讨论(0)
  • 2021-01-31 15:55

    Just do .class.getName(); in any object

    0 讨论(0)
  • 2021-01-31 15:56

    Given an instance of any object, you can call it's getClass() method to get an instance of the Class object that describe the type of the object.

    Using the Class object, you can easily print it's type name:

    Integer number=Integer.valueOf(15);
    System.out.println(number.getClass().getName());
    

    This print to console the fully qualified name of the class, which for the example is:

    java.lang.Integer
    

    If you want a more concise output, you can use instead:

    Integer number=Integer.valueOf(15);
    System.out.println(number.getClass().getSimpleName());
    

    getSimpleName() give you only the name of the class:

    Integer
    

    Printing the type of primitive variables is a bit more complex: see this SO question for details.

    0 讨论(0)
提交回复
热议问题