Java 如何获取变量名?- 爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24710487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get variable name? - java
提问by user3784463
is possible get variable name?
可以得到变量名吗?
For example:
例如:
String nameOfCar = "audi";
Now print the result:
现在打印结果:
System.out.println(nameOfCar.getVname???or something similar);
Screen:
屏幕:
nameOfCar
采纳答案by Jigar Joshi
You can get all field name by reflection
您可以通过反射获取所有字段名称
Class yourClass = YourClass.class
Field[] fields = yourClass.getFields();
for(Field f: fields){
f.getName();
}
or if you want mapping then go for Map
或者如果你想要映射然后去 Map
Map<String, String> propertyToValueMap
if you are trying to read method's local variable name, then it is not that simple to fetch also a signal that you are doing something wrong
如果您正在尝试读取方法的局部变量名称,那么获取一个表明您做错了的信号并不是那么简单
回答by Aniket Thakur
You can do it via reflection
你可以通过反射来做到
Class myClass = MyClass.class
Field field = myClass.getField("nameOfCar ");
System.out.println(field .getName());
To get all the fields without using the name you can do
要在不使用名称的情况下获取所有字段,您可以执行
Field[] myFields = myClass .getFields();