Java反射:如何获取变量的名称? [英] Java Reflection: How to get the name of a variable?

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

问题描述

使用Java Reflection,是否可以获取局部变量的名称?例如,如果我有这个:

Using Java Reflection, is it possible to get the name of a local variable? For example, if I have this:

Foo b = new Foo();
Foo a = new Foo();
Foo r = new Foo();

是否可以实现一个可以找到这些变量名称的方法,如下所示:

is it possible to implement a method that can find the names of those variables, like so:

public void baz(Foo... foos)
{
    for (Foo foo: foos) {
        // Print the name of each foo - b, a, and r
        System.out.println(***); 
    }
}

编辑:这个问题与< a href =https://stackoverflow.com/questions/9984550/is-there-a-way-in-java-to-find-the-name-of-the-variable-that-was-passed-to- a-fun>在Java中是否有办法找到传递给函数的变量的名称?因为它更纯粹地询问是否可以使用反射来确定本地名称的问题变量,而另一个问题(包括接受的答案)更侧重于测试变量值。

This question is different from Is there a way in Java to find the name of the variable that was passed to a function? in that it more purely asks the question about whether one can use reflection to determine the name of a local variable, whereas the other question (including the accepted answer) is more focused on testing values of variables.

推荐答案

从Java 8开始,可以通过反射获得一些局部变量名称信息。请参阅下面的更新部分。

As of Java 8, some local variable name information is available through reflection. See the "Update" section below.

完整信息通常存储在类文件中。一个编译时优化是删除它,节省空间(并提供一些模糊处理)。但是,当它存在时,每个方法都有一个局部变量表属性,列出局部变量的类型和名称,以及它们在范围内的指令范围。

Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.

ASM 这样的字节码工程库可能允许您在运行时检查此信息。我需要这个信息的唯一合理的地方是开发工具,因此字节码工程也可能对其他用途有用。

Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.

更新:对此有限的支持是已添加到Java 8. 现在可以通过反射获得参数(一个特殊的局部变量类)名称。除此之外,这可以帮助替换依赖注入容器使用的 @ParameterName 注释。

Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName annotations used by dependency injection containers.

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

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