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

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

问题描述

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

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(***); 
    }
}

这个问题不同于 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天全站免登陆