Print the type of a Java variable

后端 未结 6 685
囚心锁ツ
囚心锁ツ 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
    

提交回复
热议问题