在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.
}
Run Code Online (Sandbox Code Playgroud)
解决这个问题的一种方法是对每个变量类型使用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?).
Run Code Online (Sandbox Code Playgroud)
Psh*_*emo 15
根据您的示例,您似乎希望获得由变量保持的值类型,而不是声明的变量类型.所以我假设Animal animal = new Cat("Tom");你想要Cat不要Animal.
仅获取没有包部件使用的名称
String name = theVariable.getClass().getSimpleName() //to get Cat
Run Code Online (Sandbox Code Playgroud)
除此以外
String name = theVariable.getClass().getName(); //to get your.package.Cat
Run Code Online (Sandbox Code Playgroud)
variable.getClass().getName();
Run Code Online (Sandbox Code Playgroud)
返回此 Object 的运行时类。返回的 Class 对象是被表示的类的静态同步方法锁定的对象。
您可以使用该".getClass()"方法。
System.out.println(variable.getClass());
Run Code Online (Sandbox Code Playgroud)