Java 在运行时按名称间接访问变量?

标签 java reflection

这个问题有多个部分,在最后一部分都会有意义:

  1. 是否可以在运行时以编程方式列出 Java 类中任何程序员定义的变量......?

    我最近在 VB.Net 中编写了一个实用程序,它按名称列出了我项目中的所有表单,因此我可以从列表框中选择一个来运行(仅用于开发目的)。在 StackOverflow 上其他地方的帮助下,我能够将以下代码固定在一起,为了说明目的,这个例子被固定在一起......

        System.Reflection.Assembly.GetExecutingAssembly().DefinedTypes(n).BaseType.FullName
    

    在 Java 中可以做类似的事情来列出变量名吗?例如,MyInteger、MyString 或 MyObject。它就像 Visual Studio 中“Locals”窗口背后的功能(但我使用的是 Eclipse for Java)。

  2. 在过去 20 年的某个时候,在另一种编程语言中,我遇到了一个名为 Indirect(String varname) 的函数。它用于通过名称 访问原始变量。而“varname”参数本身可以是一个变量;它不一定是文字。这是一个显示其用法的示例:

    int N1, N2, N3;
    // N1, N2, & N3 are all zero
    for (int i = 1; i < 4; i++){
        Indirect("N" + i.toString) = 100
    }
    // N1, N2, & N3 are now all 100
    

    Java 是否具有与 Indirect() 等效的功能,或者是否有复制相同功能的方法......?

  3. 为了将所有这些结合在一起,以及整个论坛帖子的原因,是我编写了以下用于调试目的的程序,我将其放入我的类中以 CSV 格式输出变量值在开发过程中...

    public String listVars(){
        Object input[] = {var1, var2, var3, var4, var5};    // list of vars
        String output = "";                     // output catcher
        int varCount = input.length;            // get the length of the array
        for (int i = 0; i < varCount; i++){     // loop through the array
            output += "\"" + input[i] + "\"";   // surround with quotes, append to output
            if (i < varCount-1){                // if the item NOT the last...
                output += ",";                  // append a comma to it
            }
        }
        return output;                          // return completed output
    }
    
  4. 我想做的是使用自动枚举变量的代码自动输入对象数组,这样我就不必将它们复制并粘贴到函数中。我假设在这样做时,一旦确定了它们的名称,就需要间接引用它们,以便可以在代码中访问它们的值。

PS - 按范围过滤变量会很好,例如“private”、“super”、“”、“public”等,但我知道这可能有点过头了。=-)

最佳答案

  1. 在运行时列出类字段/方法

是的,你可以通过反射(reflection)来做到这一点。请参阅教程 here:

for (Field f : getClass().getDeclaredFields()) {
    System.out.println("found " + f);
}
  1. “间接”访问

是的,使用上面的机制找到你想要祭坛的字段然后你可以设置它的值

Field f = ... //get it from somewhere
f.set(this, "new value");

您想要实现的目标听起来非常接近 j ava bean 概念。它的要点是您要为您的 getter 和 setter 方法遵守 getX()/setX() 命名约定,每个这样的对代表一个名为“x”的属性,然后您可以利用面向 bean 的库,例如 apache commons beanutils 来为您完成所有繁重的工作(我在上面告诉过您),就像这样:

Employee employee = ...;
String firstName = (String)PropertyUtils.getSimpleProperty(employee, "firstName");
String lastName = (String)PropertyUtils.getSimpleProperty(employee, "lastName");
 ... manipulate the values ...
PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
PropertyUtils.setSimpleProperty(employee, "lastName", lastName);

关于Java 在运行时按名称间接访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281155/

相关文章:

java - 如何仅使用零参数构造函数通过 Java 反射创建具有上下文绑定(bind)的 Scala 类的新实例?

java - SocialAuth java 库未按预期工作(使用 NetBeans)

java - 在不影响 gui 其余部分的情况下运行后台作业

scala - Scala 中 Java 反射的类型安全用法

java - 使用java反射的ClassnotFound异常

java - 是否可以定义一个 Java 类加载器,它返回与所请求的完全不同的类?

c# - 将属性名称作为字符串传递到方法中 .NET

java - 更新标签内的变量

java - 为什么拆分 `(?!^)` 和 `(?&lt;!^)` 会产生相同的答案?

java - Apache 常见邮件 : Exception: Sending the email to the following server failed : smtp. gmail.com:587