在Java中,是否可以打印变量的类型?
public static void printVariableType(Object theVariable){
//print the type of the variable that is passed as a parameter
//for example, if the variable is a string, print "String" to the console.
}
解决这个问题的一种方法是为每个变量类型使用一个 if 语句,但这似乎是多余的,所以我想知道是否有更好的方法来做到这一点:
if(theVariable instanceof String){
System.out.println("String");
}
if(theVariable instanceof Integer){
System.out.println("Integer");
}
// this seems redundant and verbose. Is there a more efficient solution (e. g., using reflection?).