java 如何在Java中获取变量名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14459674/
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 in Java?
提问by Wally_the_Walrus
Possible Duplicate:
Java Reflection: How to get the name of a variable?
可能的重复:
Java 反射:如何获取变量的名称?
I've found various discussions on this topic but never any satisfying answer..
我发现了关于这个话题的各种讨论,但从来没有任何令人满意的答案..
A anyVariableName = new A();
How can I get the name of the variable anyVariableName
and get string "anyVariableName"
as a result?
Is this possible in Java?
如何获取变量的名称anyVariableName
并"anyVariableName"
作为结果获取字符串?这在Java中可能吗?
回答by JB Nizet
If anyVariableName
is a local variable, you can't. If it's a field, use Class#getField()
or Class#getDeclaredField()
.
如果anyVariableName
是局部变量,则不能。如果是字段,请使用Class#getField()
或Class#getDeclaredField()
。
回答by Peter Lawrey
The only places local variable names are stored is in the source (which you can parse) or the debug information (which you can get from the byte code if it has been included)
存储局部变量名称的唯一位置是源代码(您可以解析)或调试信息(如果包含的话,您可以从字节码中获取)
If it's a field you can use Class.getDeclaredFields() if you don't know the name.
如果它是一个字段,如果您不知道名称,您可以使用 Class.getDeclaredFields()。