Print the type of a Java variable

后端 未结 6 636
囚心锁ツ
囚心锁ツ 2020-12-24 03:24

In Java, is it possible to print the type of a variable?

public static void printVariableType(Object theVariable){
    //print the type of the variable that          


        
相关标签:
6条回答
  • 2020-12-24 03:25

    Based on your example it looks like you want to get type of value held by variable, not declared type of variable. So I am assuming that in case of Animal animal = new Cat("Tom"); you want to get Cat not Animal.

    To get only name without package part use

    String name = theVariable.getClass().getSimpleName() //to get Cat
    

    otherwise

    String name = theVariable.getClass().getName(); //to get your.package.Cat
    
    0 讨论(0)
  • 2020-12-24 03:25
    public static void printVariableType(Object theVariable){
        System.out.println(theVariable.getClass())
    }
    
    0 讨论(0)
  • 2020-12-24 03:28
    System.out.println(theVariable.getClass());
    

    Read the javadoc.

    0 讨论(0)
  • 2020-12-24 03:30
    variable.getClass().getName();
    

    Object#getClass()

    Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

    0 讨论(0)
  • 2020-12-24 03:40

    You can use the ".getClass()" method.

    System.out.println(variable.getClass());
    
    0 讨论(0)
  • 2020-12-24 03:49

    You can read in the class, and then get it's name.

    Class objClass = obj.getClass();  
    System.out.println("Type: " + objClass.getName());  
    
    0 讨论(0)
提交回复
热议问题