如何在Java中获取变量名? [英] How to get variable name in Java?

查看:73
本文介绍了如何在Java中获取变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java 反射:如何获取变量的名称?

我发现了关于这个话题的各种讨论,但从来没有任何令人满意的答案..

I've found various discussions on this topic but never any satisfying answer..

A anyVariableName = new A();

如何获取变量 anyVariableName 的名称并获取字符串 "anyVariableName" 作为结果?这在 Java 中可行吗?

How can I get the name of the variable anyVariableName and get string "anyVariableName" as a result? Is this possible in Java?

推荐答案

唯一存储局部变量名称的地方是源代码(您可以解析)或调试信息(如果有的话,您可以从字节码中获取)已收录)

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)

如果它是一个字段,如果您不知道名称,您可以使用 Class.getDeclaredFields().

If it's a field you can use Class.getDeclaredFields() if you don't know the name.

这篇关于如何在Java中获取变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆