我需要知道局部变量的类型.我正在使用Java反射,使用它我无法得到它.能告诉我如何知道局部变量的类型/名称吗?
我可以使用Java反射获取有关局部变量的信息吗?
在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)